Scala: declaring a val loop inside a loop if condition

I'm starting a scala novice and trying to understand how val works in Scala. I read that shafts cannot be changed. When I do the following:

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

currentLine is updated at each iteration, while I expect it to be initialized with the first line and hold it to the end, or at least give some reinitialization error. Why is this so? Is val created and destroyed at 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 

At the moment, I get the error "Illegal start of a simple expression." Is there any way to use x outside if?

+7
scala
source share
4 answers
  • Yes, val is created and destroyed at each iteration.

  • val x = if(condition) 2 else 3 will do what you want.

Edit: you can rewrite 2. to if(conditon) {val x = 2} else {val x = 3} (to make it compile), but that would not do anything, since if returns nothing and the variable cannot be used out if

+12
source share

For the cycle

You can break it down on map .

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

So this code is converted to

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

block can 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 line values ​​specified for the map operation.

If-else

Again, the following is not true:

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

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

 if( condition ) expression1 else expression1 

In your case, it could be:

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

However, assignment returns Unit (or void if you need an analogy with Java / C ++). Therefore, you can simply take the if-else value as follows:

 val x = if( condition ) { 2 } else { 3 } // OR val x = if( condition ) 2 else 3 
+2
source share

Not a single answer mentioned this in addition to what was said:

  • val becomes available for garbage collection at each iteration (and therefore is not available from the next iteration of the loop). This is due to what is called scope of variables , which is limited to a block in scala (same as Java).

  • As pointed out by @Kigyo val x = if(condition) 2 else 3 , you will do what you want because you only perform one assignment. If you put the binding in val in blocks, then the scope of this val is a block and therefore cannot be used the way you want.

+1
source share

1st question: yes, a new val is created at each iteration

Second question: can you rewrite it

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

All Articles