【发布时间】:2019-02-11 09:04:20
【问题描述】:
有没有办法让编译器在寻找隐含证据时以某种方式考虑类型别名?
这是我试图解决的问题示例:
// Third party library
class Foo[T, P]
class FooOps[FTP, T] {
def apply[F[_, _], P](t: T)(implicit ev: F[T, P] =:= FTP): FTP = ???
}
type StringFoo = Foo[String, Boolean]
object StringFoo extends FooOps[StringFoo, String]
StringFoo("hello")
// Attempt to wrap the third party type but have the same ops
class WrappedFoo[FTP](val foo: FTP)
object WrappedFoo {
type F[T, P] = WrappedFoo[Foo[T, P]]
}
type WrappedStringFoo = WrappedFoo[StringFoo]
object WrappedStringFoo extends FooOps[WrappedStringFoo, String]
WrappedStringFoo("hello") // Cannot prove that F[String, P] =:= WrappedStringFoo
WrappedStringFoo[WrappedFoo.F, Boolean]("hello”) // This works
我不太明白编译器如何推断类型:
StringFoo("hello")
它是否以某种方式使用可用的隐式来为F[_, _] 选择一个值?我一直认为它必须先确定类型。
但它适用于StringFoo,但不适用于WrappedStringFoo。可能是因为类型参数的数量不同。
如何获得:
WrappedStringFoo("hello")
在不明确指定类型的情况下进行编译?
【问题讨论】:
标签: scala implicit higher-kinded-types