With a type like trait A[T]
, finding an implicit in scope is simply implicitly[A[SomeType]]
Can this be done and, if so, how is this done where the type-parameter is replaced with an abstract type member, like in trait A { type T }
?
You can do
implicitly[A { type T = Int }
but you risk to lose precision:
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
To solve this problem, you can use the newly introduced the
method , from the shapeless
library (from which I've take the example above)
scala> the[Foo].t // the retains it
res1: Int = 23
scala> the[Foo].t+13
res2: Int = 36
我刚刚意识到这可以通过implicitly[A { type T = SomeType }]
完成implicitly[A { type T = SomeType }]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.