Tips for golfing in Scala
What general tips do you have for golfing in Scala? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Scala (e.g. "remove comments" is not an answer).
This has been copied from a tips question on Code Golf SE.
1 answer
Making a function with val
can be shorter than with a def
If you're pattern matching, you can use Scala's special syntax and omit match
when assigning an anonymous function to a val
. As you can see, it's a lot shorter:
val g:List[Int]=>Int={case h::t=>h+g(t)case _=>0}
def f(l:List[Int]):Int=l match{case h::t=>h+f(t)case _=>0}
You can also use underscore syntax. For certain functions, this is always profitable. For others, like the example below, where the type of the parameter cannot be inferred, it is only profitable when you have only one parameter with a type ascription.
val g=(_:Int)+1
def f(i:Int)=i+1
However, if you need to reuse a function, make a def
instead of a val
. Consider these two pairs of functions:
//Recursive
def f(i:Int):Int=if(i>0)i*f(i-1)else 1
val f:Int=>Int=i=>if(i>0)i*f(i-1)else 1
//Non-recursive functions are also shorter with def
def f(i:Int)=i+1
val g=(i:Int)=>i+1
0 comment threads