Existing solutions for hashmap with multi-type values

I am looking for a promiscuous map implementation. By heterogeneous map, I mean a structure HMap[KeyType, Any]

with specific methods:

 get[ValueType](key : KeyType] : Option[ValueType]

+(key : KeyType, value : Any) : HMap[KeyType, Any]

      

There are answers on Stack Overflow explaining how to implement it with Manifests / ClassTags, and I have a basic version:

    class TypedMap[K](

        val inner:Map[(K, TypeTag[_]), Any]){

        def +[V](key: K, value: V)(implicit tag:TypeTag[V]) = new TypedMap[K](inner + ((key, tag) -> value))

        def apply[V](key:K)(implicit tag:TypeTag[V]) = inner.apply((key, tag)).asInstanceOf[V]

        def get[V](key:K)(implicit tag:TypeTag[V]) = inner.get((key, tag)).asInstanceOf[Option[V]]

    }
    val a = new TypeMap(Map(("key1" -> 1),("key2" -> "two")))
    a.get[Int]("key1")
    a.get[String]("key2")

      

I wonder if there is a more complete implementation with additional functionality like the standard Map collection.

Usecase reads an unknown number of columns from csv / mongo / sql (some types are unknown at compile time), converts some columns (their types are known at compile time), add new ones and transfer the results to R data.frame via rJava. In my particular case, I need Map [String, Double / Int / String / Boolean / Date], if a less general solution is somehow easier.

The shortcuts for ClassTag and Manifest are described in:

How to get around style erasure in Scala? Or why can't I get the type parameter of my collections?

Scala: what is a TypeTag and how to use it?

I found some small github solutions:

https://github.com/EnMAS/EnMAS-Framework/blob/master/enmas-core/src/main/scala/org/enmas/pomdp/State.scala

https://github.com/kennknowles/scala-heterogeneous-map

What I'm not looking for:

  • Compiler mask for compile-time inference of a return type unknown at compile-time - not possible

  • Shapeless HMap - I need to distinguish between (String -> Int)

    and(String -> String)

  • It is impossible to inherit from scala.collections.Map, because for Map[A, B]

    get is get[B]

    , which in my caseget[Any]

+3


source to share





All Articles