In Previous chapter we learned about Functional Programming and today lets check out SCALA TYPE INFERENCE.

In Scala you do not have to assign datatype while declaring a variable. Scala Type Inference enables the compiler to intelligent identify the datatype based on the value assigned.

The syntax for defining a variable is as follows

var <name>: <data type> = <value>
scala> var num:Int = 5
num: Int = 5

As mentioned before providing the data type is optional. In the example below you can see that the datatype ‘num’ had not been provided with datatype but the compiler correctly identifies it.

scala> var num = 5
num: Int = 5

If you need to ask the compiler to assign a different datatype then you need to provide some hints.

scala> var num = 5
num: Int = 5

scala> var num = 5L
num: Long = 5

scala> var num = 5.0
num: Double = 5.0

scala> var num = 5.0f
num: Float = 5.0
scala> var num = "5.0"
num: String = 5.0

scala> var num = '5'
num: Char = 5

Type Inference in Function

Type Inference in function also works in similar way as variables. But first lets looks how a Scala function is defined

def <func Name> (parameters):Return DataType = {func body}

Let me create a function which takes in a number and returns the square.

scala> def sqr(num:Int) :Int = {num * num}
sqr: (num: Int)Int

scala> sqr(5)
res0: Int = 25

As you can see above a function was created ‘sqr’ and we defined the return type as INT. Lets see what happens when we don’t provide the return type in function.

scala> def sqr(num:Int) = {num * num}
sqr: (num: Int)Int

You notice that the compiler automatically identifies the return type as INT.

When not to use IT

Scala Type Inference is good until it isn’t. Its always better to mention the datatype rather than leave it to the compiler to decide. Lets say you wanted to create an Integer variable but accidentally you provided the integer with quotes[String] . If you do not provide the datatype the compiler will accept the String as you can see below in Line 1,2. But, if you would have provided the datatype the compiler would have thrown an error indicating that you are doing a wrong assignment (Line 4,8).

scala> val num = "80"
num: String = 80

scala> val num:Int = "80"
<console>:23: error: type mismatch;
 found   : String("80")
 required: Int
       val num:Int = "80"

In the next chapter we will learn about SCALA MUTABILITY VS IMMUTABILITY

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from UnderstandingBigData

Subscribe now to keep reading and get access to the full archive.

Continue reading