jump to navigation

Function references in Scala October 17, 2011

Posted by CK in Software.
Tags: , ,
trackback

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

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: