I have auto-generated scala code using slick codegen. I see that some tables Rows are implements as HLists. (but these are slick HList, not the normal shapeless HList)
Now I want a specific element from the HList returned as a Row by the slick query.
I googled and found this thread
Getting elements from an HList
But this does not work for slick HList. it works very well for Shapeless HList
I also tried the apply method
val x : Long = slickHList(2)
but this doesn't compile because type Any does not conform to exected type of Long. I would hate to do a .asInstanceOf
Is there a typesafe way in which I can access the elements of the slick HList?
Edit: Based on the input below I wrote the code below
package com.abhi
object SlickAndShapeless {
import slick.collection.heterogeneous.{HCons, HList, HNil}
import slick.collection.heterogeneous.syntax.HNil
type MyRow = HCons[Long, HCons[String, HNil]]
val row : MyRow = 1L :: "foo" :: HNil
import HListExtensions._
val hlist = row.asShapeless
val container = new Container(hlist)
val item = container.get(1)
}
class Container[L <: shapeless.HList](list: L) {
import shapeless._
import nat._
import ops.hlist._
def get(n: Nat)(implicit at: At[L, n.N]): at.Out = list[n.N]
}
object HListExtensions {
import slick.collection.heterogeneous.{HNil => SHNil, HList => SHList, HCons}
import shapeless.{::, HList, HNil}
implicit class HListShapelessSlick(val list: HList) extends AnyVal {
def asSlick : SHList = list match {
case HNil => SHNil
case head :: tail => head :: tail.asSlick
}
}
implicit class HListSlickShapeless(val list: SHList) extends AnyVal {
def asShapeless : HList = list match {
case SHNil => HNil
case HCons(head, tail) => head :: tail.asShapeless
}
}
}
The problem with the code above is that the type of item
obtained from val item = container.get(1)
is at.Out
and not Long
as I was expecting.
build.sbt
libraryDependencies ++= Seq(
"com.typesafe.slick" % "slick_2.12" % "3.2.1",
"com.chuusai" % "shapeless_2.12" % "2.3.2"
)
I also see two compiler errors
Error:(19, 35) Implicit not found: shapeless.Ops.At[shapeless.HList, shapeless.Succ[shapeless._0]]. You requested to access an element at the position shapeless.Succ[shapeless._0], but the HList shapeless.HList is too short.
val item : Long = container.get(1)
Error:(19, 35) not enough arguments for method get: (implicit at: shapeless.ops.hlist.At[shapeless.HList,shapeless.Succ[shapeless._0]])at.Out.
Unspecified value parameter at.
val item : Long = container.get(1)