0

I have to construct the Map in Scala so that I can collect all the data from call to Java code. Possible values are String, Integer, Double and null. Is there a way to represent this Map in Scala? I am trying to have Option as follow but not sure what its type should be.

def createScalaMapaFromJavaBean(): Map[String, Option[XXX]] = {
  val someJavaBean = getMyBeanValues()
  Map(
    "key1" -> Option(someJavaBean.getAgeAsInteger()),
    "key2" -> Option(someJavaBean.getSalaryAsDouble()),
    "key3" -> Option(someJavaBean.getNameAsString()),
    "key4" -> Option(someJavaBean.getSomeFieldValuesAsNull()
 )
}
αƞjiβ
  • 3,056
  • 14
  • 58
  • 95

1 Answers1

3

It's easy to do this in a type-safe way:

sealed trait MyType

case object MyNil extends MyType
case class MyInt(i: Int) extends MyType
case class MyDouble(d: Double) extends MyType
case class MyString(s: String) extends MyType

Then your code becomes:

def createScalaMapaFromJavaBean(): Map[String, MyType] = {
  val someJavaBean = getMyBeanValues()
  Map(
    "key1" -> MyInt(someJavaBean.getAgeAsInteger()),
    "key2" -> MyDouble(someJavaBean.getSalaryAsDouble()),
    "key3" -> MyString(someJavaBean.getNameAsString()),
    "key4" -> MyNil
  )
}

You might get the data back out something like this:

map.get(key) match {
  case Some(MyInt(i))    => // logic for ints
  case Some(MyDouble(d)) => // logic for doubles
  case Some(MyString(s)) => // logic for strings
  case Some(MyNil)       => // logic for nulls
  case None              => // logic for "key not found"
}
Sean
  • 29,130
  • 4
  • 80
  • 105