0

我必须在 Scala 中构建 Map,以便收集从调用 Java 代码的所有数据。可能的值为StringInteger和。有没有办法在 Scala 中表示这个地图?我试图让 Option 如下,但不确定它的类型应该是什么。Doublenull

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()
 )
}
4

1 回答 1

3

以类型安全的方式很容易做到这一点:

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

然后你的代码变成:

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

你可能会得到这样的数据:

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"
}
于 2016-05-25T22:48:15.000 回答