这是一个简化的例子。
我有以下代码:
import scala.language.implicitConversions
trait Mapping[I, O]
trait KeyMapping[K, I, O]
implicit def toMapping[I, O](s: I => O): Mapping[I, O] = ???
implicit def toKeyMapping[K, I, O](s: (K, I => O))(
implicit ev: (I => O) => Mapping[I, O]): KeyMapping[K, I, O] = ???
def test[K, I, O, M](s: M)(
implicit ev: M => KeyMapping[K, I, O]
):KeyMapping[K, I, O] = ???
val x = test(1 -> {s:String => true})
^这会产生以下错误:
type mismatch;
found: ((Int, Nothing => Boolean)) => KeyMapping[Int,Nothing,Boolean]
required: ((Int, String => Boolean)) => KeyMapping[Int,Input,Boolean]为什么会这样呢?
这个问题能解决吗?
发布于 2014-02-22 23:20:43
我使用隐式转换器而不是隐式转换来解决这个问题。
import scala.language.implicitConversions
trait Mapping[I, O]
trait KeyMapping[K, I, O]
trait MappingConverter[M, I, O] {
def convert(m: M): Mapping[I, O]
}
trait KeyMappingConverter[M, K, I, O] {
def convert(m: M): KeyMapping[K, I, O]
}
implicit def toMapping[I, O] =
new MappingConverter[I => O, I, O] {
def convert(m: I => O): Mapping[I, O] = ???
}
implicit def toKeyMapping[K, I, O, M](
implicit mapping: MappingConverter[M, I, O]) =
new KeyMappingConverter[(K, M), K, I, O] {
def convert(m: (K, M)): KeyMapping[K, I, O] = ???
}
def test[K, I, O, M](s: M)(
implicit converter: KeyMappingConverter[M, K, I, O]): KeyMapping[K, I, O] = ???
val x = test(1 -> { s: String => true })发布于 2014-02-22 01:20:38
我本来想说:
def test[K, I, O](s: (K, I => O))(
implicit ev: ((K, I => O)) => KeyMapping[K, I, O]
):KeyMapping[K, I, O] = ???没有M,注意到额外的父母。尝试一个应用程序将是自动组,而不是untuple。
您可以在2.11中使用-Ytyper-debug (2.10中的-Yinfer-debug)来查看它推断Nothing。
函数在它们的输入中是相反的,因此推断Nothing意味着它对您的I => O采用最广泛的类型。您可以进行竞争性的Mapping转换,其中之一就是Nothing。
https://stackoverflow.com/questions/21947589
复制相似问题