Scala Language Type Inference Type Inference And Generics


Example

The Scala compiler can also deduce type parameters when polymorphic methods are called, or when generic classes are instantiated:

case class InferedPair[A, B](a: A, b: B)

val pairFirstInst = InferedPair("Husband", "Wife")  //type is InferedPair[String, String]
    
// Equivalent, with type explicitly defined
val pairSecondInst: InferedPair[String, String] 
                      = InferedPair[String, String]("Husband", "Wife")  

The above form of type inference is similar to the Diamond Operator, introduced in Java 7.