Different types in Map Scala

generics, scala, shapeless

Solution

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: ... <complex type elided> ... = 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: ... <complex type elided> ... = 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.

Problem

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 `map.apply(k)` like ``` val map: Map[String, SomeType] = Map() val d: Double = map.apply("double") val str: String = map.apply("string") ``` I already tried it with a generic type ``` class Container[T](element: T) { def get: T = element } val d: Container[Double] = new Container(4.0) val str: Container[String] = new Container("string") val m: Map[String, Container] = Map("double" -> d, "string" -> str) ``` but it's not possible since `Container` takes an parameter. Is there any solution to this?

Original source

Related problems