Search code examples
scalashapelesshlist

Given a HList how do you get a HMap


I have a HList of Symbols. I want to convert this into HMap with the HList values as the keys and the value mapping set to a generated object based on the key. The generated object holds state hence though default mapping can be known subsequent state is not.


Solution

  • Well... the thing is that Shapeless HMap is not as straight forward as HList, but the following can get you started

    import shapeless._
    import poly._
    
    val hList = 'omg1 :: 'omg2 :: 'omg3 :: HNil
    
    // lets assume that you want to map Symbols to kv-pairs String -> Int
    // hence your HMap will have kv-pairs "omg1" -> 1, "omg2" -> 2...
    
    class BiMapIS[K, V]
    implicit val stringToInt = new BiMapIS[String, Int]
    
    object myFoldPolyFunc extends Poly {
      implicit def caseSymbol = use(
        (hmap: HMap[BiMapIS], elem: Symbol) =>
          hmap + (elem.name -> elem.name.last.toString.toInt)
      )
    }
    
    val hMap = hList.foldLeft(HMap.empty[BiMapIS])(myFoldPolyFunc)
    
    val v1 = hMap.get("omg1")
    // Some(1)
    
    val v2 = hMap.get("omg2")
    // Some(2)