Scala – Type Inference

  • date 27th April, 2021 |
  • by Prwatech |
  • 0 Comments

Type Inference in Scala

 

Scala Type Inference makes it optional to determine the variable type provided that type mismatch is handled. With type inference abilities, we can invest less time working out things compiler definitely knows. The Scala compiler can regularly deduce the kind of an expression so we don’t need to define it expressly.

Type inference in Scala is a powerful feature that allows the compiler to deduce the types of expressions and variables based on context, reducing the need for explicit type annotations. Scala’s type inference system leverages local type information and constraints to infer the types of expressions during compilation.

Type inference enables concise and expressive code by automatically determining the types of function parameters, return values, and intermediate variables. This reduces boilerplate code and enhances readability without sacrificing type safety.

Scala’s type inference system is sophisticated and can handle complex scenarios involving polymorphism, higher-order functions, and recursive data structures. The compiler uses unification algorithms to resolve type constraints and infer the most specific types that satisfy the program’s type requirements.

syntax

val variable_name : Scala_data_type = value

use case 1:

object prwatech {
// Main method
def main(args: Array[String])
{
// prints a double value
val x : Double = 1.93
println(x)
println(x.getClass)
} 
}

output

1.93

double

use case 2:

object prwatech {
def main(args: Array[String])
{
// type inference
println("Scala Data Types")
val number = 6
val big_number = 9000000L
val small_number = 1
val float_number = 7.50f
val double_number = 9.50
val string_of_characters = "String Characters"
val byte = 0xb
val character = "Prwatech"
val empty = ()    

println(number)
println(big_number)
println(small_number)
println(float_number)
println(double_number)
println(string_of_characters)
println(byte)
println(character)
println(empty)

} 
}

output

Scala Data Types
6
9000000
1
7.5
9.5
String Characters
11
Prwatech
()

use case 3:

    // Scala program to multiply two numbers
    object prwatech {
    // Main method
    def main(args: Array[String])
{
    // Calling the function 
    println("Product of two numbers is: " + Prod(7, 9)); 
} 


// declaration and definition of Product function 
def Prod(x:Int, y:Int) : Int =
{ 
    return x*y 
} 
}

output:

Product of two numbers is: 63

0
0

Quick Support

image image