Different types in Map Scala

后端 未结 7 1717
情书的邮戳
情书的邮戳 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:35

    If you want to do this you'd have to specify the type of Container to be Any, because Any is a supertype of both Double and String.

    val d: Container[Any] = new Container(4.0)
    val str: Container[Any] = new Container("string")
    val m: Map[String, Container[Any]] = Map("double" -> d, "string" -> str)
    

    Or to make things easier, you can change the definition of Container so that it's no longer type invariant:

    class Container[+T](element: T) {
      def get: T = element
      override def toString = s"Container($element)"
    }
    
    val d: Container[Double] = new Container(4.0)
    val str: Container[String] = new Container("string")
    val m: Map[String, Container[Any]] = Map("double" -> d, "string" -> str)
    

提交回复
热议问题