Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: declaring val within for loop, if condition

Tags:

scala

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?

like image 371
Lask3r Avatar asked Jan 28 '14 13:01

Lask3r


Video Answer


2 Answers

For Loop

You can break it down into a map operation.

for( line <- Source.fromFile(args(0)).getLines() ) {
   val currentLine = line
   println(currentLine)
}

So this code transforms to

Source.fromFile(args(0)).getLines().map( line => block )

block could be any expression. Where in your case block is:

{
   val currentLine = line
   println(currentLine)
}

Here currentLine is local to block and is created for each of the values of line given to map operation.

If-Else

Again following is also wrong:

if( some condition is satisfied) val x = 2 else val x = 3

Essentially if-else in Scala returns a value. So it should be:

if( condition ) expression1 else expression1

In your case you it can be:

if( condition ) { val x = 2 } else { val x = 3 }

However an assignment returns Unit ( or void if you want an analogy with Java / C++ ). So You can simply take the value of if-else like so:

val x = if( condition ) { 2 } else { 3 }
// OR
val x = if( condition ) 2 else 3
like image 63
tuxdna Avatar answered Oct 05 '22 23:10

tuxdna


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

  2. 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

like image 35
Kigyo Avatar answered Oct 06 '22 00:10

Kigyo