Scala: declaring val within for loop, if condition

scala

Solution

Yes, the `val` is created and destroyed on each iteration.

`val x = if(condition) 2 else 3` would do what you want.

Edit: You could rewrite 2. to `if(conditon) {val x = 2} else {val x = 3}` (to make it compile) but that would do nothing, since the if does not return anything and the variable can not be used outside the `if`

Problem

I'm a scala beginner and trying to understand how val works in Scala. I read that vals cannot be modified. When I do the following: ``` for( line <- Source.fromFile(args(0)).getLines() ) { val currentLine = line println(currentLine) } ``` currentLine is updated in each iteration, while I expect it to be initialized with the first line and hold it till the end, or at least give a re-initialization error of some sort. Why is this so? Is the val created and destroyed in each iteration? My second question: I would like to use x outside if in the following code. ``` if( some condition is satisfied) val x = 2 else val x = 3 ``` As of now, I'm getting an "Illegal start of simple expression" error. Is there a way to use x outside if?

Original source