我进一步发现它变得毛茸茸(除了我头上的头发,现在没有多少留在那里)。
我要做的是为案例类创建一个通用容器,并能够以键入的方式检索其字段,例如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
}
只是获取值有效但在编译时没有输入
我在这里遇到两个问题:
val ageByName1: Int = m1('age)
工作吗?由于