In Scala, calling a function without parameters with and without brackets is done differently

I have a Currying function declaration:

def logString(count: Int)(fun:() => Unit) {
  for (n <- 1 to count) { fun }
}

I call this function as follows:

logString(3) { () => print("I") }

As a result, there is nothing - there is simply no conclusion.

Then I just add the brackets after calling the "fun" function inside the declaration body of the Currying function:

def logString(count: Int)(fun:() => Unit) {
  for (n <- 1 to count) { fun() }
}

The result is as follows:

III

Is this some kind of Scala bug, or is there some kind of rule that I skipped while learning Scala?

I know that there is a rule when you declare a function as follows: def myFun = 1 we cannot call it with parentheses - compilation fails. But different results when calling a function with and without brackets are more like an error.

Am I right, or am I missing something about Scala?

+4
4

fun, it fun: () => Unit. , (), Unit . , fun , . .

fun: => Unit, fun , .

+6

val x = 10

. x , , .

val y = () => println("i'm a function")

, , .

scala> val x = 10
x: Int = 10

scala> val y = () => println("i'm a function")
y: () => Unit = <function0>

scala> x
res0: Int = 10

scala> y
res1: () => Unit = <function0>

:

def z() = println("i'm a function def")

.

scala> def z() = println("i'm a function def")
z: ()Unit

scala> z
i'm a function def

fun ( ).

, Scala for, fun.

, y vs y() .

+4

fun , . , .

+1

, , . , - . Scala:  - "call-by-name" - Java .  - "call-by-value" - Scala . , Single Abstract Method (SAM) .

"call-by-name" , , , . , myFunction myFunction() . "call-by-value" , , :  - - myFunction - , .  - - myFunction() - () .

:

def myFunction = 5 * 5

. , . myFunction() . : myFunction

def myFunction() = 5 * 5

. - . myFunction myFunction() - .

def myFunction = () => 5 * 5

( def val). - myFunction() - myFunction - val, .

, :

def enclosingFunc(myFunction: => Void)

. - myFunction. - myFunction() - .

includeingFunc :

enclosingFunc(n = 1; n +=1)


def enclosingFunc(myFunction: () => Int)

This is a call by value function . It is important how we call it in the aggregate of the closing function. If you call it without parentheses - myFunction - it will NOT be executed, but we just refer to the object that blocks it. If you call it using brackets - myFunction () - it will be called and executed.

In this case, includeingFunc can only be called as follows:

enclosingFunc( () => n = 1; n +=1)
0
source

All Articles