×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Misc. Topics

Scala Type Inference

By IncludeHelp Last updated : October 09, 2024

What is Type Inference in Scala?

Type interface in Scala is used to make the type declaration optional and handle all type mismatch exceptions if any occurred.

This capability of compiler makes it easier for programmers to write code. As the declaration of the data type can be left as compilers work to detect the data type.

Example without Type Inference

Let's take an example of a Scala program that declares variables with their data type,

object MyClass {
    def main(args: Array[String]) {
        var data : Double = 34.45;
        println("The data is "+ data +" and data type is "+data.getClass);
    }
}

Output

The data is 34.45 and data type is double

Example with Type Inference

Now, let's see the type inference in action,

object MyClass {
    def main(args: Array[String]) {
        var data  = 34.45;
        println("The data is "+ data +" and datatype is "+data.getClass);
    }
}

Output

The data is 34.45 and datatype is double

As you can observe, the output of both codes is the same. If the programmer does not provide the data type of the variable the compiler will do the work and give the data a type based on the data that is stored in it.

Scala Type Inference in Function

In type inference for functions, the return type of functions is omitted also the return keyword is eliminated.

Example of Type Inference in Function

Let's see an example of type inference in function,

object MyClass {
    def multiplier(a : Int , b:Int) ={
        var product = a*b; 
        product;
    }
    def main(args: Array[String]) {
        var data  = 34.45;
        println("The product of numbers is "+ multiplier(34 , 54));
    }
}

Output

The product of numbers is 1836

In the case of type inference, we need to omit the return keyword also. Otherwise, an error is returned by the compiler.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.