How to create a map type that allows you to use several types for keys and values?

I would like to create a map type, so maybe something like below:

VariantMap(1) = "Test"
VariantMap("a") = 42

and VariantMap("a")will be of type Option[Int]. Here is the code that I still have, which leads to Option[Nothing]:

object VariantMap {
  import scala.reflect.Manifest

  private var _map= Map.empty[Any,(Manifest[_], Any)] 

  def update[T](name: Any, item: T)(implicit m: Manifest[T]) {
    _map = _map(name) = (m, item)
  }

  def apply[T](key:Any)(implicit m : Manifest[T]) = {
    val o = _map.get(key)

    o match {
      case Some((om: Manifest[_], s : Any)) => Some[T](s.asInstanceOf[T])
      case _ => None
    }
  }
}

I am new to scala, so I apologize if I am missing something obvious.

+3
source share
1 answer

I am not sure if it is possible to do what you want. The apply method takes a parameter of type [T], but if you do not specify it, the compiler does not know what type T exactly represents. In this case, it does not transmit anything, a subtype of any other type.

Using your code, setting the type parameter gives the following result:


scala> VariantMap[Int]("a")
res0: Option[Int] = Some(1)

scala> VariantMap[String]("a")
res1: Option[String] = Some(1)

, , . :


object VariantMap {
   import scala.reflect.Manifest

   private var _map= Map.empty[Any,(Manifest[_], Any)] 

   def update[T](name: Any, item: T)(implicit m: Manifest[T]) {
      _map = _map(name) = (m, item)
   }

   def apply[T](key:Any)(implicit m : Manifest[T]): Option[T] = {
     val o = _map.get(key)      
     o match {
       case Some((om: Manifest[_], s : Any)) => if (om  None
     }
  }
}

scala> VariantMap("a")
res0: Option[Nothing] = None

scala> VariantMap[Int]("a")
res1: Option[Int] = Some(1)

scala> VariantMap[String]("a")
res2: Option[String] = None

, , , ( ), .

+2

Source: https://habr.com/ru/post/1748633/


All Articles