Scala 2.11.4
我有以下特质
trait MyTrait{
def met(msg: String): Unit
}
和班级
class MyClass{
def ac(mt: MyTrait) = {
//do some job
}
}
现在,我想按如下方式调用ac
:
val myClass = new MyClass
myClass.as((msg: String) => println(msg)) //meaning that just print out Strings to stdout
所以,我尝试将隐式转换添加到MyTrait
:
trait MyTrait {
def met(msgString: String): Unit
implicit def function2MyTrait(f: String => Unit): MyTrait = new MyTraitImpl(f)
private[this] class MyTraitImpl(f: String => Unit) extends MyTrait{
override def met(msgString: String): Unit = f(msgString)
}
}
但它拒绝编译:
Error:(16, 89) type mismatch;
found : String => Unit
required: com.test.trace.MyTrait
我来自Java 8.有没有办法在Scala中做这样的事情?
答案 0 :(得分:3)
function2MyTrait
需要住在伴侣对象中:
trait MyTrait {
def met(msgString: String): Unit
}
object MyTrait {
implicit def function2MyTrait(f: String => Unit): MyTrait = new MyTraitImpl(f)
private[this] class MyTraitImpl(f: String => Unit) extends MyTrait{
override def met(msgString: String): Unit = f(msgString)
}
}
Scala 2.12中不再需要这样做,因为它允许使用lambdas实现MyTrait
而无需通过String => Unit
。