Tutorial by Examples

Scala has a powerful type-inference mechanism built-in to the language. This mechanism is termed as 'Local Type Inference': val i = 1 + 2 // the type of i is Int val s = "I am a String" // the type of s is String def squared(x : Int) = x*x // the return type ...
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] // Equiv...
There are scenarios in which Scala type-inference does not work. For instance, the compiler cannot infer the type of method parameters: def add(a, b) = a + b // Does not compile def add(a: Int, b: Int) = a + b // Compiles def add(a: Int, b: Int): Int = a + b // Equivalent expression, compiles ...
Based on this blog post. Assume you have a method like this: def get[T]: Option[T] = ??? When you try to call it without specifying the generic parameter, Nothing gets inferred, which is not very useful for an actual implementation (and its result is not useful). With the following solution t...

Page 1 of 1