CodeMan
CodeMan

Reputation: 139

Is there a better way to pass optional parameters to methods in Scala?

I have the following method

def myMethod(val overrideValue: Option[Boolean] = None): Int = {
    val myValue = overridenValue.getOrElse(getDefautValue())
    // do something else
}

If I want to use the default value I call the method like this myMethod()

If I want to override the value I call the method like this myMethod(Some(true)) or myMethod(Some(false)).

Is there a better way to do this where I can omit Some(..)

Upvotes: 0

Views: 390

Answers (1)

Boris Azanov
Boris Azanov

Reputation: 4501

I think the better way to save flexibility is use method overloading:

def myMethod: Int = {
  myMethod(getDefautValue())
}

def myMethod(argumentFlag: Boolean): Int = {
    // to do something with argumentFlag
}

def getDefautValue: Boolean = ???

here you can override getDefautValue, and you don't need to wrap you boolean argument into Option. But you can have some problems if your Boolean value can be null.

Upvotes: 2

Related Questions