在Scala中使用通用数据类型值定义映射

时间:2016-05-25 22:02:25

标签: java scala scala-option

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

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

1 个答案:

答案 0 :(得分: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"
}