Vincenzo Maggio
Vincenzo Maggio

Reputation: 3869

Strange Scala compiler warning

I have the following code in Scala Play Framework:

  case class Step(name: String, f: Unit) {
    def run = {() => f}
  }

The compiler gives me a strange warning about

comparing values of type Unit and Unit using '==' will always yield true

Upvotes: 1

Views: 125

Answers (2)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297155

It's highly improbably you really need f: Unit. After all, Unit has only one value: ().

I think you might be thinking of doing this:

Step("Debugging", println("here"))

Which, indeed, respects all types, but will NOT print "here" when calling run, or applying run's return value. Instead, it will print "here" when you initialize Step, and then pass the return value, (), to f. At the point you call run, it will do nothing.

Perhaps you wanted this instead:

case class Step(name: String, f: => Unit) {
  def run = {() => f}
}

Or even:

case class Step(name: String, f: => Unit) {
  def run = f
}

Upvotes: 2

Luigi Plinge
Luigi Plinge

Reputation: 51099

It's because case classes define an == method for you, which compares each of the fields in the case class. So Step("a", println("1")) == Step("a", println("2")) is true even thought the Unit functions aren't the same.

Upvotes: 5

Related Questions