Type Inference
In this page:
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
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: