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

Type Inference

In this page:

  1. Type Inference

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}")
}
🔒

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.