Scala | Type Inference


Scala Type Inference makes it optional to specify the type of variable provided that type mismatch is handled. With type inference capabilities, we can spend less time having to write out things compiler already knows. The Scala compiler can often infer the type of an expression so we don’t have to declare it explicitly.
Let us first have a look at the syntax of how immutable variables are declared in scala.

val variable_name : Scala_data_type = value

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of type interference
object Geeks 
    
    // Main method 
    def main(args: Array[String]) 
    
        // prints a double value
        val a : Double = 7.893
        println(a)  
        println(a.getClass)
          
    

chevron_right


Output :



7.893
double

In above example the getClass method is used to print the type of the variable to the console. For the above example the type of variable ‘a’ is double.

However, through type inference, Scala automatically detects the type of the variable without explicitly specified by the user.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of type interference
object Geeks { 
  
    // Main method 
    def main(args: Array[String]) 
    
        // type inference
        println("Scala Data Types")
        val number = 5
        val big_number = 100000000L
        val small_number = 1
        val double_number = 2.50
        val float_number = 2.50f
        val string_of_characters = "This is a string of characters"
        val byte = 0xc
        val character = 'D'
        val empty = ()
          
        println(number)
        println(big_number)
        println(small_number)
        println(double_number)
        println(float_number)
        println(string_of_characters)
        println(byte)
        println(character)
        println(empty)
          
    

chevron_right


Output :

Scala Data Types
5
100000000
1
2.5
2.5
This is a string of characters
12
D
()

Note that no data type is specified explicitly for the above variables.

Scala Type Inference For Functions
Now we will have a look at how type inference works for functions in Scala.
Let’s first have a look at how functions are declared in Scala.
Syntax:

 def function_name ([parameter_list]) : [return_type] = {
   
  // function body

}

Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of multiply two numbers
object Geeks 
  
    // Main method 
    def main(args: Array[String])
    
          
        // Calling the function 
        println("Product of the two numbers is: " + Prod(5, 3)); 
    
      
      
    // declaration and definition of Product function 
    def Prod(x:Int, y:Int) : Int =
    
        return x*y 
    

chevron_right


Output :

Product of the two numbers is: 15

In above example as we can from the declaration that the specified return type is Int. With Scala type inference, Scala automatically detects the type of the function without explicitly specified by the user.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of type interference
object Geeks 
  
    def factorial(n: Int)=
          
        var f = 1
        for(i <- 1 to n) 
        
            f = f * i; 
        
          
        
    
  
    // Driver Code 
    def main(args: Array[String]) 
    
        println(factorial(5)) 
    }
  
}

chevron_right


Output :

120
def factorial(n: Int)= 

In above example colon and the return type are omitted.


Also, In above example, we have omitted the statement “return f” to “f” as we have not specified the return type.
If instead of “f”, “return f” was placed then the following error is shown by the compiler.

prog.scala:11: error: method factorial has return statement; needs result type
        return f
        ^

This shows the power of the Scala type inference, but for recursive methods, the compiler is not able to infer a result type. The above factorial function can also be implemented recursively.
The following is a recursive definition of the factorial function with no type inference.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of using recursion
object Geeks { 
  
    // factorial function
    def factorial(n: Int): Int =
    
        if (n == 0
            return 1
        else
            return n * factorial(n-1
    
  
    // Driver Code 
    def main(args: Array[String]) 
    
        println(factorial(5)) 
    
  
}

chevron_right


Output :

120

Example : With Scala type inference

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of type interference
object Geeks 
      
    // Defining function with type interfrence
    def factorial(n: Int) =
    
        if (n == 0
            1
        else
            n * factorial(n-1
    
  
    // Driver Code 
    def main(args: Array[String]) 
    
        println(factorial(5)) 
    
  
}

chevron_right


Output:

Compile Errors :
prog.scala:8: error: recursive method factorial needs result type
            n * factorial(n-1)
                ^


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.