1

I have a variable param which has to be initialized at runtime.

Then, I have a part of the code which implements the following:

if (param has been initialized)
     ...do something...
else
     print error and exit

What is the most idiomatic way to do this in Scala?

So far I have used Option[X] in this way:

var param : Option[TheType] = None
...
val param_value : TheType = x getOrElse {println("Error"); null}

But, since I have to return null it seems dirty.

How should I do it?

Aslan986
  • 9,984
  • 11
  • 44
  • 75
  • Could you provide more context? Is it a method parameter? If not providing it is an error, why allow not providing it to begin with? – johanandren Mar 15 '15 at 18:29
  • possible duplicate of [How to check for null in a single statement in scala?](http://stackoverflow.com/questions/5740906/how-to-check-for-null-in-a-single-statement-in-scala) – Aleksandar Stojadinovic Mar 15 '15 at 18:40

2 Answers2

4

Simply map or foreach over it:

param.foreach { param_value =>
  // Do everything you need to do with `param_value` here
} getOrElse sys.exit(3)  # Param was empty, kill the program

You can also use the for comprehension style:

for {
  param_value <- param
} yield yourOperation(param_value)

The upside of this is that if your calling code is expecting to do something with param_value as a return value from yourMethod you will encode the possibility of param_value not existing in your return type (it will be an Option[TheType] rather than a potentially null TheType.)

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
2

I might me wrong but it seems to me that the use of Future would fit with your problem: Instead of explicitly checking whether your required param_value has been initialized and finish the program if not, you could make your resource dependent code to execute when the resource has been rightly initialized:

val param: Future[TheType] = future {
      INITIALIZATION CODE HERE
}

param onFailure {
    case e => println("Error!");
}

param onSuccess {
    case param_value: TheType => {
        YOUR BUSINESS CODE HERE
    }
}