获取案例类参数类型作为HLIST
我正在尝试使用无形的
这用于生成foo
case class Foo(x: Int, y: String)
class Context {
val random = new Random()
}
def genInt(context: Context): Int = {
context.random.nextInt()
}
def genString(context: Context): String = {
context.random.nextString(16)
}
object ClassesToGenerators extends Poly1 {
implicit def caseInt = at[Class[Int]](_ => genInt(_))
implicit def caseString = at[Class[String]](_ => genString(_))
}
val gen = Generic[Foo]
val context = new Context()
val classes = classOf[Int] :: classOf[String] :: HNil // can't figure out how to get this hlist programmatically
val generators = classes.map(ClassesToGenerators)
gen.from(generators.zipApply(generators.mapConst(context)))
但是,我的目标是编写可重复使用的内容,例如
def newInstance[T] -> T:
???
可以生成任何仅获取int和字符串参数的情况类的实例。
如代码段中提到的那样,我坚持要获得案例类属性类型的HLIST,即想将case类foo(x:int,y:string)
转换为classof [ int] :: classof [string] :: hnil
。解决此问题的任何其他方法也非常感谢,但我并不是寻找一种生成案例类的随机实例的通用方法(因为我的用例是不同的,并且以随机生成器为例)
I'm trying to generate instances of case class using shapeless
This works for generating instances of Foo
case class Foo(x: Int, y: String)
class Context {
val random = new Random()
}
def genInt(context: Context): Int = {
context.random.nextInt()
}
def genString(context: Context): String = {
context.random.nextString(16)
}
object ClassesToGenerators extends Poly1 {
implicit def caseInt = at[Class[Int]](_ => genInt(_))
implicit def caseString = at[Class[String]](_ => genString(_))
}
val gen = Generic[Foo]
val context = new Context()
val classes = classOf[Int] :: classOf[String] :: HNil // can't figure out how to get this hlist programmatically
val generators = classes.map(ClassesToGenerators)
gen.from(generators.zipApply(generators.mapConst(context)))
However, I'm aiming to write something reusable like
def newInstance[T] -> T:
???
which could generate instances of any case classes that takes only int and string parameters.
As mentioned in the code snippet, I'm stuck at getting a hlist of case class attribute types i.e. would like to convert case class Foo(x: Int, y: String)
to classOf[Int] :: classOf[String] :: HNil
. Any other approaches to this problem are also very appreciated but I'm not looking for a generic way of generating random instances of cases classes (as my use-case is different and used random generator just as an example)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您忘记所有花哨的东西时, 无形可以更好地使用使用
hlist
:
您可以看到运行的代码
IMHO, Shapeless is better used when you forget about all the fancy stuff and just focus on simple typeclass derivation using
HList
like this:Which can be used like this:
You can see the code running here.
使用内置的无形类型类
Using built-in Shapeless type classes you can do