【问题标题】:Scala type inference and multiple arguments listScala 类型推断和多参数列表
【发布时间】:2017-06-29 18:13:59
【问题描述】:

(斯卡拉 2.11.8)

考虑以下代码:

trait Class[A] {
  def f1[B >: A](arg1: Int)(ord: Ordering[B]): Int

  def f2[B >: A](arg1: Int, ord: Ordering[B]): Int

  def f[B >: A](ord: Ordering[B]): Int = {
    f1(123)(ord) // Compilation error!
    f2(123, ord) // OK
  }
}

在此,f1(123)(ord) 行引发type mismatch; found : Ordering[B] required: Ordering[A] Note: B >: A, but trait Ordering is invariant in type T. You may wish to investigate a wildcard type such as _ >: A. (SLS 3.2.10)

如果我们将调用更改为f1[B](123)(ord),错误就会消失。

为什么存在多个参数列表会使类型检查器感到困惑?这是一个错误,还是预期的结果?

【问题讨论】:

    标签: scala type-inference typechecking


    【解决方案1】:

    这不是错误 - 参数列表的分离意味着类型参数是根据 first 参数列表单独推断的:

    f1(123)(ord) 
    

    可以改写为:

    val partiallyApplied = f1(123)
    partiallyApplied(ord)
    

    现在 - partiallyApplied 的类型是什么?由于没有显式设置类型参数,并且没有用于推理的参数/返回类型,因此类型参数被推断为A(还没有具体的B!所以partiallyApplied 的类型是@ 987654327@),因此稍后将其与Ordering[B] 一起使用会出现异常。

    相反,调用时:

    f2(123, ord)
    

    由于ord的类型为Ordering[B],因此可以推断类型参数为B,从而编译成功。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-07
      相关资源
      最近更新 更多