简体   繁体   中英

How to map HList to List[Type], List[TypeTag], or List[String]

I am playing around with the Scala REPL and its bind method. Unfortunately it takes a ClassTag which erases types some type information, eg List[Int] becomes List[_] . So I want to pass an HList to my REPL wrapper and get the type as a string which I can pass to the bind method. For this I have to map an HList to a List of strings.

def extract extends (Tuple2[String, T] ~>> String) {
    def apply[T](value: Tuple2[String, T]) = typeOf[T].toString
}

The code above is not working. For one thing I cannot use Tuple2. It should not be too hard to solve that. However, typeOf[T] requires an implicit TypeTag. Any idea how I can doe this? Could show help out?

Thanks for any help.

Try something like this,

scala> :paste
// Entering paste mode (ctrl-D to finish)

import scala.reflect.runtime.universe._
import shapeless._, poly._

object extract extends Poly1 {
  implicit def caseT[T: TypeTag] = at[(String, T)](_ => typeOf[T].toString)
}

// Exiting paste mode, now interpreting.

import scala.reflect.runtime.universe._
import shapeless._
import poly._
defined object extract

scala> val l = ("foo", 23) :: ("bar", true) :: ("baz", 2.0) :: HNil
l: ... = (foo,23) :: (bar,true) :: (baz,2.0) :: HNil

scala> l map extract
res0: String :: String :: String :: HNil = Int :: Boolean :: Double :: HNil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM