'In Scala how do you call toMap on a List of a case class?
I would like to be able to call toMap on a List of a case class:
case class Properties(name: String, value: String)
val lst = List(Properties("name1", "val1"))
lst.toMap
This doesn't work because there is no implicit evidence
Properties <:< (T,U)
so I map the list to a List[(String,String)] then call toMap.
Is there anyway of doing this without the map?
Solution 1:[1]
In general you're going to need a conversion from your case class to a Tuple2.
If your case class happens to have 2 fields and you want to key on the first field, there's an already available conversion: the companion object's unapply method:
case class Properties(name: String, value: String)
val lst = List(Properties("name1", "val1"))
lst.view.flatMap(Properties.unapply).toMap
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Levi Ramsey |
