jump to navigation

Function references in Scala October 17, 2011

Posted by CK in Software.
Tags: , ,
add a comment

I’m starting to learn Scala, and have some trouble coming to terms with its syntax. Maybe I’m spoiled by Python. In any case, here’s an example of things that I find annoying:


scala> def f(x:Int):Int = x
f: (x: Int)Int

scala> def g(f:Int=>Int, y:Int, b:Boolean):Int = if (b) g(f, y, false) else y
g: (f: (Int) => Int,y: Int,b: Boolean)Int

scala> def h=f
:6: error: missing arguments for method f in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
def h=f
^
scala> def h=f _
h: (Int) => Int

So basically, although it is fine to use just f when defining function g, in the definition of function h it is necessary to postfix f with an underscore.

I haven’t read the language reference yet, and there may be good reasons to do it like this (although I can’t think of any right now), but the inconsistency is quite confusing.

Advertisements