Scala: convert map to case class

前端 未结 6 2084
说谎
说谎 2020-12-01 01:53

Let\'s say I have this example case class

case class Test(key1: Int, key2: String, key3: String)

And I have a map

myMap = M         


        
6条回答
  •  日久生厌
    2020-12-01 02:20

    I don't love this code, but I suppose this is possible if you can get the map values into a tuple and then use the tupled constructor for your case class. That would look something like this:

    val myMap = Map("k1" -> 1, "k2" -> "val2", "k3" -> "val3")    
    val params = Some(myMap.map(_._2).toList).flatMap{
      case List(a:Int,b:String,c:String) => Some((a,b,c))
      case other => None
    }    
    val myCaseClass = params.map(Test.tupled(_))
    println(myCaseClass)
    

    You have to be careful to make sure the list of values is exactly 3 elements and that they are the correct types. If not, you end up with a None instead. Like I said, not great, but it shows that it is possible.

提交回复
热议问题