Novice here. I came across this following piece of code
class A
class B extends A
val printB: B => Unit = { b => println("Blah blah") }
Can someone explain the printB
function? I cannot understand what is b
, since it isn't defined anywhere.
Novice here. I came across this following piece of code
class A
class B extends A
val printB: B => Unit = { b => println("Blah blah") }
Can someone explain the printB
function? I cannot understand what is b
, since it isn't defined anywhere.
printB
is an anonymous function. It acts like this method:
def printBmethod(b: B): Unit = { println("Blah blah") }
Except that to make it a function, you have to eta-expand it like:
val printB = printBmethod _
See also: Difference between method and function in Scala
Explaining the lambda itself, b
is an input parameter, so you can call it like:
printB(new B)
B => Unit
means a function which takes B
and returns Unit
so scala is looking for something that takes B
and returns Unit
- like b: B => ...
P.S. The raw code without type inference for b
looks like:
val printB: B => Unit = { b: B => println("Blah blah") }
So here you see what actually b
is.