coder25
coder25

Reputation: 2393

check optional field to populate another field

Is there any efficient way to remove the below if and else condition

object Currency {

  sealed trait MyConstants extends MyTrait[String]
  case object A extends MyConstants {val value ="abc"}
  case object B extends MyConstants {val value = "def"}

}

case class Test(name:String)
case class MyCurerncy(currency: Option[MyConstants])
 def check (name:String):Option[Test] ={.....}
 if(check("xyz").isDefined){
    MyCurerncy(Option(Currency.A))
 }else{
    None
 }

The method check return the Option[Test] .I need to populate MyCurrency based on the condition if Test is defined or not.

Upvotes: 0

Views: 61

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51658

MyCurerncy(Option(Currency.A)) is of type MyCurerncy. None is of type Option[Nothing]. So

 if(check("xyz").isDefined){
    MyCurerncy(Option(Currency.A))
 }else{
    None
 }

will be of type Any (actually Product with Serializable but it doesn't matter). Are you sure you prefer to have Any?

If you prefer to have MyCurerncy i.e.

 if(check("xyz").isDefined){
    MyCurerncy(Option(Currency.A))
 }else{
    MyCurerncy(None)
 } 

you can write

MyCurerncy(check("xyz").flatMap(_ => Option(Currency.A)))

If you anyway prefer Any you can write as you wrote or match

  check("xyz") match {
    case Some(_) => MyCurerncy(Option(Currency.A))
    case None => None
  }

Upvotes: 1

Related Questions