我可以从HList获取一个类型化值

时间:2017-10-06 15:57:42

标签: scala shapeless

我进一步发现它变得毛茸茸(除了我头上的头发,现在没有多少留在那里)。

我要做的是为案例类创建一个通用容器,并能够以键入的方式检索其字段,例如var x:Int = m('年龄)

这是一个小设置:

import shapeless._
import ops.hlist._
import ops.record.{Keys, Values}

case class Bar(name: String, age: Int)

class Morphic[H <: HList](h: H) {
  def apply[S <: Symbol, K <: HList, V <: HList](s: S)(implicit
                                                       keys: Keys.Aux[H, K],
                                                       values: Values.Aux[H, V],
                                                       ktl: ToList[K, Any],
                                                       vtl: ToList[V, Any]) = {
    import shapeless.record._
    (h.keys.toList zip h.values.toList).toMap.getOrElse(s, None) // <-- is there a way to achive this without going through Map
  }

  def apply(n: Nat)(implicit at: At[H, n.N]): at.Out = h(at)
}

object Morphic {
  def apply[A, H <: HList](p: A)(implicit gen: LabelledGeneric.Aux[A, H]) = {
    new Morphic(gen.to(p))
  }
}

object testApp extends App {

  var f = Bar("John", 25)
  var m1 = Morphic(f)
  val ageByName = m1('age)
  println(s"ageByName(value=${ageByName}, type=${ageByName.getClass})")
  val ageByPos = m1(1)
  println(s"ageByName(value=${ageByPos}, type=${ageByPos.getClass})")

  //val ageByName1: Int = m1('age) // <-- compile time error, Any does not match Int
  //val ageByPos1: Int = m1(1)  // <-- compile time error, at.Out does not match Int

  // As I want to do this without using asInstanceOf(Int)
  // val isAdult: Boolean = ageByName > 22
}

只是获取值有效但在编译时没有输入

我在这里遇到两个问题:

  1. 我可以让val ageByName1: Int = m1('age)工作吗?
  2. 在给定符号的情况下检索HList值的更简单的方法是什么(希望这样我可以将它分配给具有指定类型的var)
  3. 由于

0 个答案:

没有答案
相关问题