What limits does scala place on the "acceptable complexity" of inferred types?

ScalaType Inference

Scala Problem Overview


According to the 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.

In practice what are the limits?

Also, are there different limits that apply to inferred expression types than to parameter type bounds, and what are those limits?

Scala Solutions


Solution 1 - Scala

When inferring types, the compiler often needs to calculate the Least Upper Bound (LUB) of a list of types. For example, the type of if (cond) e1 else e1 is the LUB of the types of e1 and e1.

These types can get quite large, for example try this in a 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]...

This commit introduced some sanity checks to limit the depth of such inferred types.

There has been some recent work to plugin to the compilation process to detect inferred types that take a long time to calculate, and suggest places where an explicit type annotation might be prudent.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOwenView Question on Stackoverflow
Solution 1 - ScalaretronymView Answer on Stackoverflow