Idiomatic form of dealing with un-initialized var
Question: I'm coding up my first Scala script to get a feel for the language, and I'm a
bit stuck as to the best way to achieve something.

My situation is the following, I have a method which I need to call N times,
this method returns an Int on each run (might be different, there's a random
component to the execution), and I want to keep the best run (the smallest
value returned on these runs).

Now, coming from a Java/Python background, I would simply initialize the
variable with null/None, and compare in the if, something like:

    
    
    best = None
    for...
        result = executionOfThings()
        if(best is None or result < best):
            best = result
    

And that's that (pardon for the semi-python pseudo-code).

Now, on Scala, I'm struggling a bit. I've read about the usage of Option and
pattern matching to achieve the same effect, and I guess I could code up
something like (this was the best I could come up with):

    
    
    best match {
        case None => best = Some(res)
        case Some(x) if x > res => best = Some(res)
        case _ =>
      }
    

I believe this works, but I'm not sure if it's the most idiomatic way of
writing it. It's clear enough, but a bit verbose for such a simple "use-case".

Anyone that could shine a functional light on me?

Thanks.


Answer: For this _particular_ problem, not in general, I would suggest initializing
with `Int.MaxValue` as long as you're guaranteed that `N >= 1`. Then you just

    
    
    if (result < best) best = result
    

You could also, with `best` as an option,

    
    
    best = best.filter(_ >= result).orElse( Some(result) )
    

if the optionality is important (e.g. it is possible that `N == 0`, and you
don't take a distinct path through the code in that case). This is a more
general way to deal with optional values that may get replaced: use `filter`
to keep the non-replaced cases, and `orElse` to fill in the replacement if
needed.

