Q: Changing between var and val in Scala leads to logical checks behaving differently I was working with Project Euler Problem 4 (finding the largest palindrome formed from the product of two three-digit numbers), and produced the solution euler4_1, which uses a variable cand. The function runs as expected, iterating through all pairs (i, j) and only replacing cand with a bigger palindrome.
def euler4_1(): Int = {

    var cand=0

    for(i <- 100 until 999){
        for(j <- 100 until i){
          if (((i*j).toString.reverse == (i*j).toString)&&(i*j>cand)){
            cand=i*j
            println(cand)
            }
        }
    }

    return cand
    }

    /** 
    ...
    666666
    678876
    696696
    749947
    819918
    824428
    828828
    861168
    888888
    906609
     */

However, initializing cand as a var instead of a val seems to mess things up - a number of palindromes which are smaller than the current best are also printed out.
def euler4_2(): Int = {

    val cand=0

    for(i <- 100 until 999){
        for(j <- 100 until i){
          if (((i*j).toString.reverse == (i*j).toString)&&(i*j>cand)){
            val cand=i*j
            println(cand)
            }
        }
    }

    return cand
    }

    /** 
    ...
     601106
     650056
     853358
     141141
     282282
     119911
     906609
     514415
     580085
     */

What's happening in the second code sample, labelled euler4_2?
[Comments on how to make the code more idiomatic in scala are also appreciated].

A: As n.m. pointed out in the comments, the problem is that you have two different val's named cand. If you want to write this in functional style, without any var's, use foldLeft and pass cand through each iteration:
(100 until 999).foldLeft(0) { (cand, i) =>
  (100 until i).foldLeft(cand) { (cand, j) =>
    val product = i * j
    val productS = product.toString
    if (productS.reverse == productS && product > cand) {
      println(product)
      product
    } else cand
  }
}


A: scala> (for (i <- 100 until 999 ;
     |       j <- 100 until i;
     |       ij = i * j;
     |       ijs = ij.toString if ijs == ijs.reverse
     |      ) yield ij
     | ).max
res0: Int = 906609

would be the most obvious (to me) idiomatic functional-style implementation using comprehensions. Not sure about efficiency though.
