有以下代码,无法弄清楚如何实现(主要是访问)并执行在对象内定义的特征方法“toTest”。
object Main extends App {
object A {
trait Test[T] {
def toTest(in: T): String
def apply[T: Test](in: T): String = implicitly[Test[T]].toTest(in)
}
}
答案 0 :(得分:1)
未修改的代码:
scala> object Main extends App {
|
| object A {
| trait Test[T] {
| def toTest(in: T): String
|
| def apply[T: Test](in: T): String = implicitly[Test[T]].toTest(in)
| }
| }
| }
defined module Main
scala> new Main.A.Test[Int]{ override def toTest(in: Int) = in.toString }.toTest(123)
res0: String = 123
简化为:
scala> object Main extends App {
|
| object A {
| trait Test[T] {
| def toTest(in: T): String
|
| def apply(in: T): String = toTest(in)
| }
| }
| }
defined module Main
scala> new Main.A.Test[Int]{ override def toTest(in: Int) = in.toString }.toTest(123)
res2: String = 123
scala> (new Main.A.Test[Int]{ override def toTest(in: Int) = in.toString })(123)
res6: String = 123