I often find myself doing things like:
println(foo)
when I'd like to do:
println foo
The compiler does not allow this.
Also, println is a mouthful, I really just want to say:
echo foo
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.
Now, how do I invoke echo without needing to wrap the Any to print in parens?
Method # 1: Using the “println” Command The “println” command in the Scala programming language is used to print a line while introducing a new line at the end.
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable. Because val fields can't vary, some people refer to them as values rather than variables.
Difference between Scala Functions & Methods: Function is a object which can be stored in a variable. But a method always belongs to a class which has a name, signature bytecode etc. Basically, you can say a method is a function which is a member of some object.
object ∊ {def cho(s: Any) {println(s)}}
∊cho "Hello world"
will save your fingers.
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.
You could also
object echo {def -(s: Any) {println(s)}}
echo-"Hello world"
which works pretty well IMO.
YEARS LATER EDIT: another almost-solution, using StringContext:
implicit class PimpMyString(sc: StringContext) {
def echo(args: Any*) = println(sc.raw(args: _*))
}
echo"Hello World"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With