Why does my reassignment of a function value fail in Scala?
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?
onTrade
is a function, so you need to use parentheses in order to call it:
def run {
onTrade()
}
Update
Method run
most 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?
精彩评论