2014-02-21 46 views
0

这是一个简单的例子类型推断和隐式链接

我有以下代码:

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] 

这是为什么?

可以解决这个问题吗?

回答

0

我解决了它通过使用隐式转换器而不是隐式转换。

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 }) 
1

我正想说:

def test[K, I, O](s: (K, I => O))(
     implicit ev: ((K, I => O)) => KeyMapping[K, I, O] 
):KeyMapping[K, I, O] = ??? 

号男,并注意额外的括号。它会autotuple尝试一个适用,但不是未实现。

你可以(在2.10 -Yinfer-debug)在2.11使用-Ytyper-debug看到它推断Nothing

功能在它们的输入中是相反的,因此推断Nothing意味着它的最宽类型为I => O。您可以竞争Mapping转换,其中之一需要Nothing

+0

我其实需要'M',我忘了说这是个简单的例子 – EECOLOR