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
Scala Path Dependent Type
Scala Path Dependent Types (PDTs) are an advanced feature of the Scala language that allows users to create types that are dependent on the path in which they are accessed. The type of a variable or object is not determined by its own structure or characteristics, but rather by the path in which it
4 min read
Data Types in Scala
A data type is a categorization of data which tells the compiler that which type of value a variable has. For example, if a variable has an int data type, then it holds numeric value. In Scala, the data types are similar to Java in terms of length and storage. In Scala, data types are treated same o
3 min read
How to Overcome Type Erasure in Scala?
Type erasure may provide challenges in Scala, particularly when dealing with generics. Type tags and manifests are a means to prevent type erasure. By preserving type information during runtime, these approaches let you operate with genuine types as opposed to erased types. Table of Content What is
3 min read
Scala | Tuple
Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. An example of a tuple storing an integer, a string, and boolean value. val name = (15, "Chandan", tr
5 min read
What is Lifting in Scala?
Scala is a programming language that is expressive and effective. It permits builders to produce code that is both elegant and succinct. Lifting is one such belonging that is vital to useful programming paradigms. Functions may fit easily on values interior containers, such as Option, List, Future,
3 min read