[英]Scala traits and implicit conversion confusion
The following lines work when I enter them by hand on the Scala REPL (2.7.7): 当我在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! 谢谢!
Functions can't be defined at the top level. 无法在顶层定义函数。 Put myTraitToString
in a (companion, if you like) object: 将myTraitToString
放在(如果你喜欢的话)伴侣中:
object myTrait {
implicit def myTraitToString(input : myTrait) : String = input.ToString
}
And then bring it into scope: 然后将其纳入范围:
import myTrait._
Whenever myTraitToString is in scope -- ie when you could call it without any dots -- it will be applied implicitly. 每当myTraitToString在范围内时 - 即当你可以在没有任何点的情况下调用它时 - 它将被隐式应用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.