Reputation: 395
I am trying to generate the list of intervals which are not included in a given list starting from 1. So I wrote the code as shown below:
def comparatorInt(first: (Int,Int), second: (Int, Int)) = first._2 <= second._1
val list1 = List((93,97), (5,10),(15,20),(30,50), (76,90)).sortWith(comparatorInt)
var curr = 1
val res = for(x <- list1; tmp = curr; curr = x._2+1) yield(tmp,x._1-1)
Here I am getting an compiler error
Error: forward reference extends over definition of value tmp
lazy val res = for(x <- list1; tmp = curr; curr = x._2+1) yield(tmp,x._1-1)
I am not able to figure out the fix for the issue. Kindly suggest a solution for the same.
Upvotes: 0
Views: 1412
Reputation: 40500
The other answer explains well enough why you are getting the error. I just wanted to add: do not use var
, you don't need them most of the time. If you are writing in scala might as well take advantage of the power of the language and stay idiomatic, rather than just writing same old java code with funny syntax :)
Consider something like this:
((0,0) :: list1).foldRight(List.empty[(Int,Int)]) {
case(x@(a, b), res@((c, d) :: tail)) if(b < c-1) => x :: (b+1, c-1) :: res
case(x, res) => x :: res
}.tail
(Besides not causing a compilation error, this version also works correctly, unlike yours, that has logical errors ;)).
Upvotes: 1
Reputation: 1285
The curr
in the for
comprehension is not the same one as your var
. What you wrote is equivalent to
var curr = 1
val res = for(x <- list1; tmp = anotherCurr; anotherCurr = x._2+1) yield(tmp,x._1-1)
so the compiler sees that you are trying to define temp
before you defined anotherCurr
, hence the error.
If you want to modify the var
, you can do it after the yield
operation.
Upvotes: 3