使用 like 的类型trait A[T]
,在范围内查找隐式很简单implicitly[A[SomeType]]
可以这样做吗?如果可以,在类型参数被替换为抽象类型成员的情况下,如何做到这一点,例如 in trait A { type T }
?
使用 like 的类型trait A[T]
,在范围内查找隐式很简单implicitly[A[SomeType]]
可以这样做吗?如果可以,在类型参数被替换为抽象类型成员的情况下,如何做到这一点,例如 in trait A { type T }
?
你可以做
implicitly[A { type T = Int }
但您可能会失去精度:
scala> trait Foo { type T ; val t: T }
defined trait Foo
scala> implicit val intFoo: Foo { type T = Int } = new Foo { type T = Int ; val t = 23 }
intFoo: Foo{type T = Int} = $anon$1@6067b682
scala> implicitly[Foo].t // implicitly loses precision
res0: Foo#T = 23
要解决这个问题,您可以使用库中新引入的the
方法(我从shapeless
上面的示例中获取)
scala> the[Foo].t // the retains it
res1: Int = 23
scala> the[Foo].t+13
res2: Int = 36
我刚刚意识到这可以用implicitly[A { type T = SomeType }]