Frank Frank - 1 month ago 8
Scala Question

Tuple and if in Scala

I am getting a compile time error with the following code:

val bestModel = model
val bestEvals: List[Double] = null

... <code, including code that initializes bestEvals> ...

(bestModel, bestEvals) = if (allAgreeBetter)
(updatedModel, currentEvals.map {case (eval, _) => eval}.toList)
else
(bestModel, bestEvals)


The error is (are):

Error:(203, 34) ';' expected but '=' found.
(bestModel, bestEvals) = if (allAgreeBetter)
Error:(205, 11) ';' expected but 'else' found.
else


What did I miss? If I take out this statement, the code compiles and runs fine, so the problem is specifically in this statement.

Answer

As mentioned here, you can't have tuple assignments to pre-existing references - it's something that Scala does not support.

The only similar pattern that would indeed work would be:

var (bestModel, bestEvals) = if (allAgreeBetter) ...

However, if bestModel and bestEvals were pre-declared, then you would be redeclaring them (and not assigning them a new value).

Hope this helps!

Cheers.

Comments