我写了一些代码,它在伴随对象中获取了一些隐含的值,如下所示:
package example.implicits
class Test {
import Test.GetValue
import Test.Implicits._
val intV = getV[Int]
val stringV = getV[String]
private def getV[T](implicit getV: GetValue[T]): T = getV.value
}
object Test {
trait GetValue[T] {
def value: T
}
object Implicits {
implicit val intValue = new GetValue[Int] {
def value = 10
}
implicit val stringValue = new GetValue[String] {
def value = "ten"
}
}
}
Run Code Online (Sandbox Code Playgroud)
这段代码无法编译,编译器抱怨它无法找到所需的隐含值.请注意我的环境是
Java HotSpot(TM)64位服务器VM上的scala 2.11.8,Java 1.8.0_66
但是,如果我明确使用这些值,则没有错:
class Test {
import Test.GetValue
import Test.Implicits._
val …Run Code Online (Sandbox Code Playgroud)