In Scala, I’d like to do:
class Identifier(val str: String) {
override def toString(): String = str
}
class Variable(t: Type, name: Identifier, mutable: Boolean) {
override def toString(): String = name
}
But I can’t because Scala won’t implicitly convert name in Variable#toString()‘s definition to a String. Is there a way this can be achieved ?
To be clear: I don’t want to define an additional method like:
object Identifier {
implicit def idToString(x: Identifier): String = x.str
}
I’d like the toString() method to be called to do the conversion.
Try putting an explicit
toString()call after calling name inVariablestoString method like so:Here you will explicitly call the method converting
Variableto a string, thus telling the compiler exactly what you want... Unless you really require the method to be implicit…