deltanovember
deltanovember

Reputation: 44051

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?

Upvotes: 2

Views: 226

Answers (1)

tenshi
tenshi

Reputation: 26566

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?

Upvotes: 8

Related Questions