WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Scala · Guru · question 84 of 100

What are the limitations of Scala’s type inference mechanism, and how do they compare to other languages with more advanced type inference algorithms?

📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

Scala’s type inference mechanism is powerful but has some limitations compared to more advanced type inference algorithms found in languages like Haskell. Here are some of its limitations:

1. **Local type inference**: Scala’s type inference is local to a particular function, value, or block of code. It doesn’t infer types across the entire body of the program, which means you sometimes need to provide explicit type annotations, especially for function return types. In contrast, languages like Haskell use global type inference (Hindley-Milner algorithm), which doesn’t require specifying as many type annotations.

2. **Upper bounds on polymorphic types**: Scala has issues with inferring the most general type for expressions involving polymorphic methods, classes, and traits. It infers the upper bound of their common supertype, leading to a more specific type than intended. Explicit type annotations are required to guide the type checker in such cases.

trait BadTypeInference[T]
case class SpecificType(x: Int) extends BadTypeInference[String]

val instance = SpecificType(42)

In the example above, Scala infers ‘BadTypeInference[Any]‘ as the type for ‘instance‘, but the expected type would be ‘BadTypeInference[String]‘.

3. **Higher-kinded types**: Scala struggles with inferring types for higher-kinded types (also known as type constructors) correctly. This often requires providing explicit type annotations or using ‘Aux‘ pattern to help the type checker.

trait HigherKinded[F[_], A]
def Id[A](x: A): A = x

val inferred = implicitly[HigherKinded[Id.type, Int]]

In the example above, Scala is not able to infer the correct type for ‘inferred‘ without explicit type annotation.

4. **Path-dependent types**: Type inference for path-dependent types can be complex as well, often leading Scala to infer a more specific type than intended. Providing explicit type annotation can help resolve the ambiguity.

Despite these limitations, Scala’s type inference mechanism is still considered to be powerful by industry standards. It strikes a balance between expressiveness, type safety, and readability.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview — then scores it.
📞 Practice Scala — free 15 min
📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

All 100 Scala questions · All topics