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:
Syntax
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
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}")
}
Login to try C/C++/Java/PHP code in the editor
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
- Leaving a type off a method's public parameters, such as
def add(a, b), when parameters always need explicit types. - Expecting
val x = 10to be usable as aDoublelater, when it is inferred asInt. - Relying on inference for an empty list like
val xs = List(), which is inferred asList[Nothing]and is hard to use.
🔒
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: