scala - scala 对推断类型的 "acceptable complexity"有什么限制?

标签 scala type-inference

根据Scala Language Spec :

... local type inference is permitted to limit the complexity of inferred bounds [of type parameters]. Minimality and maximality of types have to be understood relative to the set of types of acceptable complexity.



在实践中有何限制?

此外,适用于推断表达式类型的限制是否与适用于参数类型边界的限制不同,这些限制是什么?

最佳答案

在推断类型时,编译器通常需要计算类型列表的最小上限 (LUB)。例如if (cond) e1 else e1的类型是 e1 类型的 LUB和 e1 .

这些类型可能会变得非常大,例如在 REPL 中试试这个:

:type Map(1 -> (1 to 10), 2 -> (1 to 10).toList)
scala.collection.immutable.Map[Int,scala.collection.immutable.Seq[Int] with scala.collection.AbstractSeq[Int] with Serializable{def reverse: scala.collection.immutable.Seq[Int] with scala.collection.AbstractSeq[Int]{def reverse: scala.collection.immutable.Seq[Int] with scala.collection.AbstractSeq[Int]; def dropRight(n: Int): scala.collection.immutable.Seq[Int] with scala.collection.AbstractSeq[Int]; def takeRight(n: Int): scala.collection.immutable.Seq[Int] with scala.collection.AbstractSeq[Int]; def drop(n: Int): scala.collection.immutable.Seq[Int] with scala.collection.AbstractSeq[Int]; def take(n: Int): scala.collection.immutable.Seq[Int] with scala.collection.AbstractSeq[Int]}; def dropRight(n: Int): scala.collection.immutable.Seq[Int] with scala.collection.AbstractSeq[Int]{def reverse: scala.collection.immutable.Seq[Int] with scala.collection.AbstractSeq[Int]; def dropRight(n: Int): scala.collection.immutable.Seq[Int]...

commit引入了一些健全性检查来限制此类推断类型的深度。

最近有一些工作插入到编译过程中,以检测需要很长时间计算的推断类型,并建议显式类型注释可能谨慎的地方。

关于scala - scala 对推断类型的 "acceptable complexity"有什么限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11425350/

相关文章:

java - 如何将 lambda 类型强制为特定类型?

c++ - 有什么方法可以获取 "current function"的返回类型

json - 如何使用 JSON Writes 将日期写入 ISO 8601 格式?

scala - 如何在 Scala 中定义 @interface?

scala - 使用返回 future 的函数遍历列表和流

scala - 在匹配情况下使用模式绑定(bind)器进行类型推断无法按预期工作

java - 如何将 ArrayList<SubClass> 作为 ArrayList<BaseClass> 传递

scala - sonatype 发布中的 "No Staging repository found"问题

scala - 从 Cassandra 读取数据在 Flink 中处理

C# 5.0 泛型 : param type inference