Scala (4): anonymous function

We can transfer anonymous function or save it as variable.

val addOne = (x: Int) => x + 1
addOne(1) // output: 2

If your function has more than one lines, you’d better use {} to clarify it.

{i: Int =>
  println("hello world")
  i * 2

Another concept is anonymous parameter. You can use _ to apply another function. _ means a magic wildcard which hasn’t named, which expresses different things in different contexts. In { 2 + _}, _ means a anonymous parameter.

def addr(m: Int, n: Int) = m + n
val add2 = addr(2, _:Int)

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s