首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型推断与隐式链接

类型推断与隐式链接
EN

Stack Overflow用户
提问于 2014-02-21 23:58:16
回答 2查看 60关注 0票数 0

这是一个简化的例子。

我有以下代码:

代码语言:javascript
复制
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})
            ^

这会产生以下错误:

代码语言:javascript
复制
type mismatch;
found: ((Int, Nothing => Boolean)) => KeyMapping[Int,Nothing,Boolean]
required: ((Int, String => Boolean)) => KeyMapping[Int,Input,Boolean]

为什么会这样呢?

这个问题能解决吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-02-22 23:20:43

我使用隐式转换器而不是隐式转换来解决这个问题。

代码语言:javascript
复制
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 })
票数 0
EN

Stack Overflow用户

发布于 2014-02-22 01:20:38

我本来想说:

代码语言:javascript
复制
  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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21947589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档