mchl_k
mchl_k

Reputation: 314

Assign a value based on if condition in Scala

I have a while loop that needs to create an object based on a condition happening inside the loop. The code runs fine but the object is not available once the loop finishes.

I suspect I am missing something about how variable scope works in Scala.

If what I am trying is not possible, I would like to understand why and what the alternatives are.

This is a simple example

var i = 0

while (i < 5) {
    val magicValue = if (i==2) i
    i += 1
}

println(magicValue) // error: not found: value magicValue

This is how I would do it in python

i = 0

while i<5:
    if (i==2):
        magic_value = i
    i += 1

print(magic_value) # prints 2

Upvotes: 1

Views: 1130

Answers (3)

isarikaya
isarikaya

Reputation: 112

Please read this article read

You should use var instead of val. If you use val, this value cannot be used except in the if scope.

var i = 0
var magicValue = 0
while (i < 5){
  if(i==2) magicValue = i
   i += 1
}
println(magicValue)

demo

Each variable declaration is preceded by its type.
By contrast, Scala has two types of variables:
val creates an immutable variable (like final in Java)
var creates a mutable variable

Upvotes: -4

Tomer Shetah
Tomer Shetah

Reputation: 8529

You can do:

println(0.to(5).find(_ == 2).getOrElse(0))

find will return an Option, in case there is an element that satisfies the condition. If there is such, it will be printed. Otherwise, the default 0 will be printed.

For example:

println(0.to(5).find(_ == 20).getOrElse(0))

will print 0.

There is also a findLast method, in case you want the last that satisfies this condition:

println(0.to(5).findLast(_ == 2).getOrElse(0))

Code run at Scastie.

Upvotes: 3

jwvh
jwvh

Reputation: 51271

In the same way you wouldn't feed bird-seed to a dog, you shouldn't try to write Python code using Scala. Learning a new language is more than new syntax. It's also new idioms and new ways to think about problem solving.

val magicValue = (0 to 5).foldLeft(0){
                       case (mv,i) => if (i==2) i else mv}

Upvotes: 3

Related Questions