Reputation: 12202
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.
Upvotes: 4
Views: 2551
Reputation: 1715
If you just want 'odd' ways of doing this then you can use member import
class Variable(t: Type, name: Identifier, mutable: Boolean) {
import name.{toString => toStr}
override def toString(): String = toStr
}
you cannot do import name.toString
as this gets hidden by all other toString
s methods in Any
etc
Upvotes: 1
Reputation: 11237
override def toString(): String = name.toString
is not terribly taxing on the fingers
Upvotes: 0
Reputation: 2710
Try putting an explicit toString()
call after calling name in Variables
toString method like so:
override def toString() = name.toString()
Here you will explicitly call the method converting Variable
to a string, thus telling the compiler exactly what you want.
.. Unless you really require the method to be implicit...
Upvotes: 6