这是一个简化的例子
我有以下代码:
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]
为什么是这样?
这可以解决吗?
我通过使用隐式转换器而不是隐式转换来解决它。
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 })
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句