As my mind was wandering off earlier today, I started to wonder what it would take to create a Ruby puts
or PHP echo
statement in Scala. (For some reason my brain can never type “println,” and puts or echo are much easier to type.)
One simple way to mimic a puts
or echo
method is to use Scala's ability to rename things on import:
scala> import System.out.{println => echo} import System.out.{println=>echo} scala> import System.out.{println => puts} import System.out.{println=>puts} scala> echo("foo") foo scala> puts("foo") foo scala> puts(1 + 1) 2
This is a start. I've been thinking about creating my own "Al Predef" class, and if I ever do, I'll include something like this in it.
Note that this approach works because
out
is a static member in the JavaSystem
class, andprintln
is a method in that static member.
What I’d really like
What I’d really like to be able to do is type something like this:
echo "foo bar"
or
puts "foo bar"
but ... I don’t know how to do that. I do know how to reverse these statements so I can write something like this:
"foo bar baz" echo
To make that happen, just extend the String class using an implicit conversion, like this:
class AlStuff(val s: String) { def echo { println(s) } } implicit def stringToString(s: String) = new AlStuff(s) // works "four score and seven years ago" echo // works "four score and" + " seven years ago" echo // works "Hello, %s".format("Al") echo