簡體   English   中英

如何使用Map實例創建Scala案例類實例

[英]How to create a scala case class instance with a Map instance

我想創建一個scala案例類,其字段來自地圖。 而且,這是案例類

 case class UserFeature(uid: String = null,
                     age: String = null,
                     marriageStatus: String = null,
                     consumptionAbility: String = null,
                     LBS: String = null,
                     interest1: String = null,
                     interest2: String = null,
                     interest3: String = null,
                     interest4: String = null,
                     interest5: String = null,
                     kw1: String = null,
                     kw2: String = null,
                     kw3: String = null,
                     topic1: String = null,
                     topic2: String = null,
                     topic3: String = null,
                     appIdInstall: String = null,
                     appIdAction: String = null,
                     ct: String = null,
                     os: String = null,
                     carrier: String = null,
                     house: String = null
                          )

假設地圖實例是

Map("uid" -> "4564131",
    "age" -> "5",
    "ct" -> "bk7755")

如何將地圖的鍵和值應用於案例類的字段和值?

您可以執行UserFeature(uid = map_var("uid"), age = map_var("age"), ct = map_var("ct"))假設保存Map的變量是map_var並且鍵可用

使用null表示缺少的字符串值不是一個好主意。 請改用Option[String]

case class UserFeature(uid: Option[String] = None,
                       age: Option[String] = None,
                       marriageStatus: Option[String] = None,
                       ...

完成后,您可以使用地圖上的get來檢索值。

UserFeature(map.get("uid"), map.get("age"), map.get("marriageStatus") ...)

地圖中存在的值將為Some(value) ,缺失值將為None Option類有許多用於以安全方式處理可選值的有用方法。

合成另外兩個答案,我會將UserFeature中你默認為null所有String轉換為null (除非與編寫UserFeature Java代碼進行交互,否則你基本上不應該在Scala中使用它,甚至用它就像可能)到Option[String] 我將搜索和替換留給了答案。

然后你可以這樣做:

object UserFeature {
  def apply(map: Map[String, String]): UserFeature =
    UserFeature(map.get("uid"), map.get("age") ...)
}

哪個讓你用:

val someMap: Map[String, String] = ...
val userFeature = UserFeature(someMap)

通過更改Option[String] ,您的代碼庫中還需要進行一些其他更改。 https://danielwestheide.com/blog/2012/12/19/the-neophytes-guide-to-scala-part-5-the-option-type.html是如何處理Option的好教程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM