← Back to Scala Course | Chapter 2: Variables & Types | Lesson 6 of 8

Type Inference

Type inference means Scala can figure out what kind of thing a value is without you saying so, like guessing an animal from its picture. It saves typing while staying safe.

In this page:

  1. Type Inference
Syntax
scala
val name = value          // type inferred
var other = value
def method_name(param: Type) = expression

Type Inference

Scala's compiler can infer a val/var's type from its initializer, so val x = 10 is understood as Int without an explicit annotation.

The value is still statically typed -- inference is a compile-time convenience, not dynamic typing. Explicit type annotations are still useful for public APIs, since they document intent and don't rely on the initializer being obvious.

Note: Type inference is a compile-time feature -- the type is fixed at compile time even though you didn't write it out.

Example: Type Inference

markup
object Main extends App {
  val count = 10        // inferred as Int
  val name = "Alice"    // inferred as String
  val price = 19.99     // inferred as Double

  println(s"${count.getClass.getSimpleName} ${name.getClass.getSimpleName} ${price.getClass.getSimpleName}")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Leaving a type off a method's public parameters, such as def add(a, b), when parameters always need explicit types.
  2. Expecting val x = 10 to be usable as a Double later, when it is inferred as Int.
  3. Relying on inference for an empty list like val xs = List(), which is inferred as List[Nothing] and is hard to use.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.