0

使用 like 的类型trait A[T],在范围内查找隐式很简单implicitly[A[SomeType]]

可以这样做吗?如果可以,在类型参数被替换为抽象类型成员的情况下,如何做到这一点,例如 in trait A { type T }

4

2 回答 2

2

你可以做

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
于 2014-08-20T22:59:35.413 回答
1

我刚刚意识到这可以用implicitly[A { type T = SomeType }]

于 2014-08-20T20:45:40.143 回答