简体   繁体   中英

Scala function definition vs application

Why does f in the following code snippet gives the value of 1. I was expected f() to be 1. How can I obtain a reference to the function f:()=> Int

var y = 0
def f():Int = {y + 1}

f

Somethings in scala drive me nuts.

If you're calling a function that has no parameters, then you can drop the brackets. That's why f evaluates to 1.

The exact same expression can also evaluate into a function reference if the compiler knows that you're expecting a value of that type.

val foo: () => Int = f

You can obtain so using _ :

  var y = 0
  def m:Int = {y + 1}
  val result = m _  // type of result is an instance of Function0 "() => Int"

Use _ when compiler is not expecting Function object.

If you want f to be an expression of type () => Int that evaluates to { y + 1 } , then just define it as such:

var y = 0
val f: () => Int = () => { y + 1 }

Now

f

does nothing (it just gives back the lambda of type () => Int ), but

f()

gives 1 .

You don't really need the type ascription, this works too:

val f = () => { y + 1 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM