Using `puts` or `echo` instead of `println` in Scala

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.

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

That only works with Strings

As you can see, this works when 'echo' gets a String, but if I try it with other things like this:

1 + 1 echo

it won't work (unless I add an implicit conversion to handle Int objects as well, in this case).

I'm sure I'll dig into this more in the future, because there are several other things like this I'd like to be able to do, especially in my Scala scripts, but for today, that's a quick look at adding echo and puts functions in Scala.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.