7

The following lines work when I enter them by hand on the 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 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!

1
  • 1
    as i noticed in REPL definitions are implicitly put inside a class. Commented Apr 18, 2010 at 8:57

1 Answer 1

13

Functions can't be defined at the top level. Put myTraitToString in a (companion, if you like) object:

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

And then bring it into scope:

import myTrait._

Whenever myTraitToString is in scope -- i.e. when you could call it without any dots -- it will be applied implicitly.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.