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:
Scala
// 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)
}
}
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 :
Scala
// 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)
}
}
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 :
Scala
// 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
}
}
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 :
Scala
// Scala program of type interference
object Geeks
{
def factorial(n: Int)= {
var f = 1
for(i <- 1 to n)
{
f = f * i;
}
f
}
// Driver Code
def main(args: Array[String])
{
println(factorial(5))
}
}
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 :
Scala
// 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))
}
}
Output :
120
Example : With Scala type inference
Scala
// Scala program of type interference
object Geeks
{
// Defining function with type interference
def factorial(n: Int) =
{
if (n == 0)
1
else
n * factorial(n-1)
}
// Driver Code
def main(args: Array[String])
{
println(factorial(5))
}
}
Output:
Compile Errors :
prog.scala:8: error: recursive method factorial needs result type
n * factorial(n-1)
^
Similar Reads
Scala AnyRef type The Scala kind hierarchy starts with Any, that's the supertype of all types. The direct subclasses of Any are AnyVal and AnyRef. Whereas AnyVal represents price kinds (which includes Int, Double, and so on.), AnyRef represents reference types. AnyRef serves because the fundamental type and root deta
3 min read
Scala Type Hierarchy There are no primitive types in Scala(unlike Java). All data types in Scala are objects that have methods to operate on their data. All of Scala's types exist as part of a type hierarchy. Every class that we define in Scala will also belong to this hierarchy automatically. AnyAny is the superclass o
3 min read
Scala Any type In Scala, the Any class is at the top of the hierarchy of classes. Scala stands like the supertype of all types and provides a foundation for Scala's type system. Any is like a supertype from which all values in scala are inherited whether it is a value type like(Int, Double, Float, etc.) or a refer
7 min read
Type Casting in Scala A Type casting is basically a conversion from one type to another. In Dynamic Programming Languages like Scala, it often becomes necessary to cast from type to another.Type Casting in Scala is done using the asInstanceOf[] method. Applications of asInstanceof methodThis perspective is required in ma
4 min read
Higher-Kinded Types in Scala This article focuses on discussing Higher-Kinded types in Scala. What is the Higher-Kinded Type? A higher-kinded type is a type that can stand for other types, which themselves stand for more types. It's a way to talk about types that are built from other types. They let us write code that can handl
4 min read