score:2

Accepted answer

pattern matching is a good option to make dr a val, especially if you need to test a for multiple different values.

val a = 10

val dr = a match {
  case 10 => true
  case _ => false
}

print(dr)

case 10 => true this essentially says "if a matches 10, then assign true to dr"
case _ = false this says "if none of the above case(s) matched a then assign false to dr"

note that dr will be a boolean type in the above sample, which is much better than using a string to represent true/false. if you really need a string for some reason then you would do.

val dr = a match {
  case 10 => "true"
  case _ => "false"
}

print(dr)

score:1

if you use a val, you're not allowed to assign it a new value, so in your code example above, if you switch the third line with

val fa2 = fa.:+(ra)

then fa can be a val.

score:1

the pattern matching is probably the best style for this case, but if you wanted the if else you could write is as this. note in scala when the if statement is evaluated it returns a result like any other code block.

val a = 10
val dr = if (a == 10) {
   "true"
}
else {
    "false"
}
println("dr: " + dr)

score:1

i'll just add, that perhaps instead of representing dr as a string it would be better to type it as a boolean, and then you can simply evaluate it to the result of the condition:

val a = 10
val dr = a == 10
println("dr: " + dr)

score:4

in scala, if/else is an expression that returns a value.

val dr = if (condition) value1 else value2

Related Query

More Query from same tag