Home » Scala language

Type Inference in Scala

Type interface is used to make the declaration of data type optional. In this tutorial on the Scala Type interface, we will learn about the type interface in Scala along with some examples.
Submitted by Shivang Yadav, on December 17, 2019

Scala Type Interface

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.

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

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

We have seen the type inference for variables. Now, let's see type inference in function. In type inference for functions, the return type of functions is omitted also the return keyword is eliminated.

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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.