Hana
Hana

Reputation: 1470

How to get return value from if else block

I want to define a val called Options using a Map function. env is an argument parameter that can either be "dev" or "prod." I want to be able to access the val outside of if statement. How can I fix this? Here is what I have:

val sfOptions = ""
    if (env == "prod") {
      val sfOptions = Map(
        "sfURL" -> "XXX", "sfUser" -> "XXX", "sfRole" -> "XXX", "sfPassword" -> "XXX",
        "sfDatabase" -> "XXX", "sfSchema" -> "XXX", "sfWarehouse" -> "XXX"
      )
    } else if (env == "dev") {
      val sfOptions = Map(
        "sfURL" -> "XXX", "sfUser" -> "XXX", "sfRole" -> "XXX", "sfPassword" -> "XXX",
        "sfDatabase" -> "XXX", "sfSchema" -> "XXX", "sfWarehouse" -> "XXX"
      )
    }

Upvotes: 1

Views: 811

Answers (2)

Anoop Bandi
Anoop Bandi

Reputation: 56

Probably the simplest way is to assign the value of sfOptions using the result of a match expression. In this case, something like this:

val sfOptions = env match {
  case "prod" => Map(
        "sfURL" -> "XXX", "sfUser" -> "XXX", "sfRole" -> "XXX", "sfPassword" -> "XXX",
        "sfDatabase" -> "XXX", "sfSchema" -> "XXX", "sfWarehouse" -> "XXX"
      )
  case "dev" => Map(
        "sfURL" -> "XXX", "sfUser" -> "XXX", "sfRole" -> "XXX", "sfPassword" -> "XXX",
        "sfDatabase" -> "XXX", "sfSchema" -> "XXX", "sfWarehouse" -> "XXX"
      )
}

Edit: To do this specifically with an if-else statement, take a look at Raman's post. Because every statement in Scala can return a value, whether that be match or if-else, you can use them directly with an assignment operator.

Upvotes: 4

Raman Mishra
Raman Mishra

Reputation: 2686

In addition to the accepted answer, I would like to add some background and concept scala uses. So first of all in scala if and else are function not expression hence if else also returns value so we can use if else something like this.

val result: Boolean = if (condition) 
   true 
else 
   false

As we can see if condition matches we will have true in result otherwise false.

Mostly it's recommended that for trivial match we should go with if and else not pattern matching. In your case we can go with if and else.

val sfOptions : Map[String, String] = if (env == "prod") {
    Map("sfURL" -> "XXX", "sfUser" -> "XXX", "sfRole" -> "XXX", "sfPassword" -> "XXX",
        "sfDatabase" -> "XXX", "sfSchema" -> "XXX", "sfWarehouse" -> "XXX")
    } else {
Map("sfURL" -> "XXX", "sfUser" -> "XXX", "sfRole" -> "XXX", "sfPassword" -> 
     "XXX","sfDatabase" -> "XXX", "sfSchema" -> "XXX", "sfWarehouse" -> "XXX")
    }

You need to keep that in mind that both your condition block return the same data type here Map[String, String] else you will get the return type as any and then you won't be able to use val sfOptions as you want.

Upvotes: 3

Related Questions