开发者

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜