Showing posts with label z9850| Type Inferrence. Show all posts
Showing posts with label z9850| Type Inferrence. Show all posts

Specifying Explicit Type : Type annotation

PS:45, psn > a15 > a70
There are situations where type cannot be inferred by Scala. The process of specifying explicit type in Scala is called as Type Annotation. Here are scenarios where Type Annotation is required
  1. When no value is assigned for a variable
  2. Method parameters require Type Annotation
scala> //Example : Type Annotation for Function Parameter

scala> def fn(val no) = "This is a demo"
<console>:1: error: identifier expected but 'val' found.
       def fn(val no) = "This is a demo"
              ^

scala> def fn(no) = "This is a demo"
<console>:1: error: ':' expected but ')' found.
       def fn(no) = "This is a demo"
                ^

scala> def fn(no:Int) = "This is a demo"
fn: (no: Int)String

Recursive Function

// PS:43, psn > a15 > 160
// Scala type inference cannot infer the return type of recursive
// function

// @tailrec Annotation can be used to check tail-call optimization

Expression, Type Inferrence & Return Value

// Here we have explicitly specified the Type
scala> val no:Int = 10
no: Int = 10

// Last statement in an expression is considered as
// return value
// Scala infers the Type when we do not explicitly
// specify the Type
scala> val result1 = if (no == 10) {
     |    "good"
     | } else {
     |    "bad"
     | }
result1: String = good

// When Scala is not able to able to infer a Specific Type to
// a variable, a type of 'Any' is assigned to that variable
scala> val result2 = if (no == 10) {
     |    "good"
     | }
result2: Any = good