Tips for golfing in Scala

The shortest way of repeating something is with Seq.fill.

1 to 10 map(_=>println("hi!")) // Wrong!
for(i<-1 to 10)println("hi!") // Wrong!
Seq.fill(10)(println("hi!")) // Right!

suspicious identifier: ?

You can use ? as identifier:

val l=List(1,2,3)
val? =List(1,2,3)

Here it doesn't save you anything, because you can't stick it to the equal sign:

val ?=List(1,2,3) // illegal

But later on, it often saves one character, since you don't need a delimiter:

print(?size)  // l.size needs a dot
def a(? :Int*)=(?,?tail).zipped.map(_-_)

However, it is often tricky to use:

       print(?size)
3
       print(?size-5)
<console>:12: error: Int does not take parameters
       print(?size-5)
              ^

Collections

The first choice for a random collection is often List. In many cases you can replace it with Seq, which saves one character instantan. :)

Instead of

val l=List(1,2,3)
val s=Seq(1,2,3)

and, while s.head and s.tail is more elegant in usual code, s(0) is again one character shorter than s.head.

Even shorter in some cases - depending on needed functionality is a tuple:

val s=Seq(1,2,3)
val t=(1,2,3)

saving 3 characters immediately, and for accessing:

s(0)
t._1

it is the same for direct index access. But for elaborated concepts, tuples fail:

scala> s.map(_*2)
res55: Seq[Int] = List(2, 4, 6)

scala> t.map(_*2)
<console>:9: error: value map is not a member of (Int, Int, Int)
       t.map(_*2)
         ^

update

def foo(s:Seq[Int])
def foo(s:Int*)

In parameter declaration, Int* saves 4 characters over Seq[Int]. It is not equivalent, but sometimes, Int* will do.