Different types in Map Scala

后端 未结 7 1698
情书的邮戳
情书的邮戳 2020-12-14 03:11

I need a Map where I put different types of values (Double, String, Int,...) in it, key can be String.

Is there a way to do this, so that I get the correct type with

7条回答
  •  死守一世寂寞
    2020-12-14 03:38

    This is now very straightforward in shapeless,

    scala> import shapeless._ ; import syntax.singleton._ ; import record._
    import shapeless._
    import syntax.singleton._
    import record._
    
    scala> val map = ("double" ->> 4.0) :: ("string" ->> "foo") :: HNil
    map: ...  ... = 4.0 :: foo :: HNil
    
    scala> map("double")
    res0: Double with shapeless.record.KeyTag[String("double")] = 4.0
    
    scala> map("string")
    res1: String with shapeless.record.KeyTag[String("string")] = foo
    
    scala> map("double")+1.0
    res2: Double = 5.0
    
    scala> val map2 = map.updateWith("double")(_+1.0)
    map2: ...  ... = 5.0 :: foo :: HNil
    
    scala> map2("double")
    res3: Double = 5.0
    

    This is with shapeless 2.0.0-SNAPSHOT as of the date of this answer.

提交回复
热议问题