简体   繁体   中英

What does “()” stand for in: val f = {() => x += 1}

My question is about Scala function:

var x = 1
val f = {() => x += 1}

It's clear if the function literal looks like:

val f = (x:Int)=>x+1

But what does () stand for in:

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

I am pretty new in Scala. I've read out the function chapter in a Scala book already, but still cannot understand what () means here.

tl;dr It's just an empty argument list of a function.

It's an empty argument list. It means you're not passing any arguments to the function. So normally that kind of function would not consume any value, but would supply value when it's called.

Your case is special. Variable x comes from the outer scope and is bound to your function so it becomes closure. Every time you invoke f it will change the value of x .

The () in the val f = {() => x += 1} represents the function takes no argument and increase value of x by 1

it is similar to

var x = 1
def foo(): Unit = {
    x += 1
}


val f: () => Unit = () => x += 1

This is not a pure function

f is of type () => Unit . A function that takes no arguments and returs nothing (Unit)

val f: () => Unit = {() => x += 1}

The java equivalent of this would be the Supplier interface.

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