Reputation: 69
I want to create a scala case class whose fields come form a map . And , here is the case class
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
)
suppose the map instance is
Map("uid" -> "4564131",
"age" -> "5",
"ct" -> "bk7755")
how can I apply the keys&values of the map to the fields&values of case class?
Upvotes: 3
Views: 2844
Reputation: 20611
Synthesizing the other two answers, I would convert all the String
s in UserFeature
that you're defaulting to null
(which you should basically never use in Scala unless interacting with poorly-written Java code requires it, and even then use it as little as possible) to Option[String]
. I leave that search-and-replace out of the answer.
Then you can do:
object UserFeature {
def apply(map: Map[String, String]): UserFeature =
UserFeature(map.get("uid"), map.get("age") ...)
}
Which lets you use:
val someMap: Map[String, String] = ...
val userFeature = UserFeature(someMap)
With the change to Option[String]
, there will be some other changes that need to be made in your codebase. https://danielwestheide.com/blog/2012/12/19/the-neophytes-guide-to-scala-part-5-the-option-type.html is a good tutorial for how to deal with Option.
Upvotes: 1
Reputation: 1964
You can do UserFeature(uid = map_var("uid"), age = map_var("age"), ct = map_var("ct"))
assuming the variable holding Map
is map_var
and the keys are available
Upvotes: 1
Reputation: 27421
It is not a good idea to use null
to represent missing string values. Use Option[String]
instead.
case class UserFeature(uid: Option[String] = None,
age: Option[String] = None,
marriageStatus: Option[String] = None,
...
Once you have done that, you can use get
on the map to retrieve the value.
UserFeature(map.get("uid"), map.get("age"), map.get("marriageStatus") ...)
Values that are present in the map will be Some(value)
and missing values will be None
. The Option
class has lots of useful methods for processing optional values in a safe way.
Upvotes: 1