【问题标题】:Why do I need an explicit evidence type / why does this Scala type bound fail?为什么我需要一个明确的证据类型/为什么这个 Scala 类型绑定失败?
【发布时间】:2012-01-18 07:44:18
【问题描述】:

下面,第一种情况成功,第二种失败。为什么我需要一个明确的证据类型/为什么这个 Scala 类型绑定失败?类型推断器在解决A 时的特殊限制是什么?

scala> implicit def view[A, C](xs: C)(implicit ev: C <:< Iterable[A]) = new { def bar = 0 } 
view: [A, C](xs: C)(implicit ev: <:<[C,scala.collection.immutable.Iterable[A]])java.lang.Object{def bar: Int}

scala> view(List(1)) bar
res37: Int = 0

scala> implicit def view[A, C <: Seq[A]](xs: C) = new { def bar = 0 } 
view: [A, C <: scala.collection.immutable.Seq[A]](xs: C)java.lang.Object{def bar: Int}

scala> view(List(1)) bar
<console>:149: error: inferred type arguments [Nothing,List[Int]] do not conform to method view's type parameter bounds [A,C <: scala.collection.immutable.Seq[A]]
              view(List(1)) bar
              ^

【问题讨论】:

    标签: scala


    【解决方案1】:

    我真的不知道为什么会发生这种情况,尽管我的直觉是它与Seq 的类型参数的差异有关。不过,我可以让以下工作:

    implicit def view[A, C[~] <: Seq[~] forSome { type ~ }](xs: C[A]) = 
       new { def bar = 0 } 
    

    你想要C 有什么原因吗?我的意思是,你打算在方法中使用C 吗?因为如果不是,为什么不只是

    implicit def view[A](xs: Seq[A]) = new { def bar = 0 }
    

    ?

    【讨论】:

    • 是的,否则我根本不需要xs。这是为需要知道AC 的皮条客准备的。至于更高种类型的解决方案,请参阅我的其他评论。
    【解决方案2】:

    不幸的是,类型推断不能很好地处理由同一类型参数列表(此处为 A)中的其他类型参数(类型包含)界定的类型参数(例如 C)。

    使用隐式参数对约束进行编码的版本不受此限制的影响,因为隐式施加的约束与类型参数边界施加的约束分开求解。

    您还可以通过将 xs 的类型拆分为抽象集合 (CC) 的类型构造函数和抽象其元素的(正确的)类型 (A) 来避免循环,如下所示:

    scala> implicit def view[A, CC[x] <: Seq[x]](xs: CC[A]) = new { def bar = 0 } 
    view: [A, CC[x] <: Seq[x]](xs: CC[A])Object{def bar: Int}
    
    scala> view(List(1)) bar
    res0: Int = 0
    

    CC等类型的更多详情,请查看What is a higher kinded type in Scala?

    【讨论】:

    • 谢谢,但我实际上知道C[A] &lt;: Seq[A] 有效 - 它只是将我限制为一元类型构造函数。我想要C &lt;: Seq[A]。无论如何,你回答了我的问题,说推理不能很好地处理相互引用的类型参数,所以我会将其标记为已接受,但会喜欢更多细节!
    猜你喜欢
    • 1970-01-01
    • 2010-10-17
    • 2011-03-19
    • 2017-06-22
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多