scala - Type transformation with shapeless -
i have class similar this:
class myclass[t <: hlist] { val x: ??? } my problem type of x val. i'd have hlist each type u of t hlist replaced option[u]. i.e. if specify:
new myclass[int :: string :: hnil] i x have type of option[int] :: option[string] :: hnil
is possible? how it?
you'll need mapped instance witnesses t , type of x have relationship:
import shapeless._, ops.hlist.mapped abstract class myclass[t <: hlist, ot <: hlist](implicit mapped: mapped.aux[t, option, ot] ) { val x: ot } unfortunately kind of inconvenient instantiate:
new myclass[int :: string :: hnil, option[int] :: option[string] :: hnil] { val x = some(0) :: some("") :: hnil } there ways around this, require additional changes. example, allow both type parameters inferred:
import shapeless._, ops.hlist.comapped class myclass[t <: hlist, ot <: hlist](val x: ot)(implicit mapped: comapped.aux[ot, option, t] ) and then:
new myclass(option(0) :: option("") :: hnil) or can use closer original class custom constructor in companion object:
import shapeless._, ops.hlist.mapped abstract class myclass[t <: hlist] { type ot <: hlist def mapped: mapped.aux[t, option, ot] val x: ot } object myclass { class partiallyapplied[t <: hlist] { def apply[ot0 <: hlist](x0: ot0)(implicit mapped0: mapped.aux[t, option, ot0] ): myclass[t] = new myclass[t] { type ot = ot0 val mapped: mapped.aux[t, option, ot] = mapped0 val x: ot = x0 } } def apply[t <: hlist]: partiallyapplied[t] = new partiallyapplied[t] } and then:
myclass[int :: string :: hnil](option(0) :: option("") :: hnil) which of these approaches more appropriate depend on how you're using class.
Comments
Post a Comment