In the following code I try to create a function value that takes no parameters and prints a message
trait Base {
var onTrade = () => println("nothing")
def run {
onTrade
}
}
In the following subclass I try to reassign the function value to print a different message
class BaseImpl extends Base {
onTrade = () => {
val price = 5
println("trade price: " + price)
}
run
}
When I run BaseImpl nothing at all is printed to the console. I’m expecting
trade price: 5
Why does my code fail?
onTradeis a function, so you need to use parentheses in order to call it:Update
Method
runmost probably confuses you – you can call it even without parentheses. there is distinction between method and function. You can look at this SO question, it can be helpful:What is the rule for parenthesis in Scala method invocation?