问题描述
我经常发现自己在做以下事情:
I often find myself doing things like:
println(foo)
我想做的事情:
println foo
编译器不允许这样做。
此外,println令人a舌,我真的只想说:
Also, println is a mouthful, I really just want to say:
echo foo
因此,在基本包对象中,我创建了println的回显版本:
So, in a base package object I created the echo version of println:
def echo(x: Any) = Console.println(x)
容易,回声应用范围广,很棒。
Easy enough, have echo application wide, great.
现在,如何调用echo而不需要将Any包装在括号中?
Now, how do I invoke echo without needing to wrap the Any to print in parens?
推荐答案
object ∊ {def cho(s: Any) {println(s)}}
∊cho "Hello world"
会节省您的手指。
∊是Unicode Sm集中的数学符号,因此在Scala中算作运算符,因此在字母数字字符旁边不需要空格。
It works because ∊ is a math-symbol in the Unicode Sm set, hence counts as an operator in Scala, so doesn't require spaces when placed next to alphanumeric characters.
您也可以
object echo {def -(s: Any) {println(s)}}
echo-"Hello world"
在IMO上效果很好。
以后编辑:另一个几乎解决方案,使用StringContext:
YEARS LATER EDIT: another almost-solution, using StringContext:
implicit class PimpMyString(sc: StringContext) {
def echo(args: Any*) = println(sc.raw(args: _*))
}
echo"Hello World"
这篇关于Scala更好的println的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!