Scala – Type Inference

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

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.

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

Quick Support

image image