Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala a better println

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?

like image 785
virtualeyes Avatar asked Apr 09 '12 11:04

virtualeyes


People also ask

What is Println in Scala?

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.

What is the meaning of => in Scala?

=> 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 .

What is difference between Val and VAR in Scala?

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.

What is the difference between method and function in Scala?

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.


1 Answers

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"
like image 189
Luigi Plinge Avatar answered Nov 15 '22 07:11

Luigi Plinge