How to use conditional statements when overriding toString

Viewed 174

I'm trying to override toString using conditional statements. But I'm getting an error that says there is a type mismatch. It is supposed to be in String type and right now it's in Any type. noGoals, Tied are functions that returns true or false.

override def toString = {
  if (this.noGoals)
    s"${this.home} vs. ${this.away} at ${this.location}: no goals"
  else if (this.Tied)
    s"${this.home} vs. ${this.away} at ${this.location}: tied"
}




    
1 Answers

The expression

if (conditionA) "aa"
else if (conditionB) "bb"

defaults to

if (conditionA) "aa"        
else if (conditionB) "bb"   
else ()                     // oops () types to Unit

where value () has Unit type, whilst values "aa" and "bb" have type String, and least upper bound of Unit and String is Any. Thus try providing default string to the last else branch like so

if (conditionA) "aa"
else if (conditionB) "bb"
else "default"
Related