Scala traits and implicit conversion mixing

The following lines work when I enter them manually in Scala REPL (2.7.7):

trait myTrait { override def toString = "something" } implicit def myTraitToString(input: myTrait): String = input.toString object myObject extends myTrait val s: String = myObject 

However, if I try to compile a file with it, I get the following error:

 [error] myTrait.scala:37: expected start of definition [error] implicit def myTraitToString(input: myTrait): String = input.toString [error] ^ 

Why?

Thanks!

+7
scala traits implicit conversion
source share
1 answer

Functions cannot be defined at the top level. Put myTraitToString in the object (companion, if you want):

 object myTrait { implicit def myTraitToString(input : myTrait) : String = input.ToString } 

And then enter it into scope:

 import myTrait._ 

Whenever myTraitToString is in scope - i.e. when you can call it without any points, it will be applied implicitly.

+13
source share

All Articles