'Strange behavior during variables assignment in Scala

How can I define variables inside if-block ?

if ( 2 > 1  ){
    val t = 6
}
print(t)

This simple code returns error : not found: value t



Solution 1:[1]

Your code's t variable is only defined within if block. So you can use it only inside this block. One reason for this behavior is a question: Which value has t when the condition of the if statement is false.

If you want to use the t variable outside this scope you can do the following:

  1. Put if block in the assigning like this:
val t = if (2 > 1) 0 else 1
  1. Use var keyword to make the t mutable and define it before if block with the default value:
var t = 1

if (2 > 1) {
  t = 0
}

In any case, you need a value for else case to be able to define the t variable.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sierikov