Scala: implicit conversion using a method (e.g. toString)

In Scala, I would 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 cannot, because Scala will not imply converting name in Variable#toString() to String. Is there a way this can be achieved?

To be clear: I do not want to define an additional method, for example:

 object Identifier { implicit def idToString(x: Identifier): String = x.str } 

I would like the toString() method to be called for conversion.

+4
source share
3 answers

Try adding an explicit call toString() after calling the name in the Variables toString method as follows:

 override def toString() = name.toString() 

Here you explicitly call the Variable to string conversion method, thereby telling the compiler exactly what you want.

.. If you really do not want the method to be implicit ...

+6
source

If you just need the β€œodd” ways to do this, you can use member imports

 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 is hidden by all other toString methods in Any etc.

+1
source
 override def toString(): String = name.toString 

not scared of fingers

0
source

Source: https://habr.com/ru/post/1399633/


All Articles