Scala 类型推断和多参数列表 [英] Scala type inference and multiple arguments list

查看:51
本文介绍了Scala 类型推断和多参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(Scala 2.11.8)

(Scala 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] 注意:B >: A,但 trait Ordering 在类型 T 中是不变的.您可能希望调查通配符类型,例如 _ >: A.(SLS 3.2.10)

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

If we change the call to f1[B](123)(ord), error disappears.

为什么存在多个参数列表会混淆类型检查器?这是错误还是预期结果?

Why does the presence of multiple arguments list confuses the typechecker? Is this a bug, or an expected result?

推荐答案

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

It's not a bug - the separation into parameter lists means that the type parameter is inferred based on the first argument list alone:

f1(123)(ord) 

可以改写为:

val partiallyApplied = f1(123)
partiallyApplied(ord)

现在 - partiallyApplied 的类型是什么?由于未明确设置类型参数,并且没有用于推理的参数/返回类型,因此类型参数被推断为 A(还没有特定的 B! 所以 partiallyApplied 的类型是 (Ordering[A]) => Int),因此将它与 Ordering[B] 一起使用后给出例外.

Now - what is partiallyApplied's type? Since the type parameter wasn't explicitly set, and there's no argument / return type to use for inference, the type parametter is inferred to be A (there's no specific B yet! So partiallyApplied's type is (Ordering[A]) => Int), hence using it with Ordering[B] later gives the exception.

相反,调用时:

f2(123, ord)

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

Since ord has type Ordering[B], the type parameter can be inferred to be B, hence compilation succeeds.

这篇关于Scala 类型推断和多参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆