2

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?

deltanovember
  • 42,611
  • 64
  • 162
  • 244

1 Answers1

8

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?

Community
  • 1
  • 1
tenshi
  • 26,268
  • 8
  • 76
  • 90
  • 1
    Interesting thanks. So what does onTrade actually do? (without the parentheses) – deltanovember Sep 17 '11 at 21:43
  • @deltanovember: literally nothing :) in this case method `run` just returns this function, but since you defined your method like this, return value would be just ignored (the actual return type of `run` is `Unit`) – tenshi Sep 17 '11 at 21:46
  • I believe it just uses it like a normal variable if you do that. (please confirm someone better with Scala than I) – Gunnar Hoffman Sep 17 '11 at 21:46
  • 1
    @Gunnar Hoffman: yes, it's treated as a value. You can pass it as an argument to other function/method or return it, but important thing is that this function would not be called/evaluated unless you call it explicitly with the help of parentheses. – tenshi Sep 17 '11 at 21:50
  • Also, it's recommendable to always write your method return type. – Carlos López-Camey Sep 17 '11 at 22:07