Go Back

How we can achive Type Inference in scala

All Articles

#program #scala # #Type Inference in scala

How we can achive Type Inference in scala

Type Inference in scala 

As long as type mismatch is addressed, Scala Type Inference makes determining the variable type should be optional.
Scala has a feature called type inference that enables the compiler to infer the data types of variables, expressions, and functions based on their usage and context. Otherwise put,
Without explicit type annotations, the Scala compiler can infer the types of values at compilation time.
import scala.collection.immutable._
object ArrayTest
  def main(args: Array[String])
     var arr = Array(1,2,3,4,5)      // Creating single dimensional array
    def show(){
      for(a<-arr)                       // Traversing array elements
      println("Third Element  = "+ arr(2))        // Accessing elements by using index


In Example 1, the variable arr  is assigned a Array value, 
and the compiler automatically deduces that the type of arr is Array.