1

Suppose I have a tuple

val myTuple: (String,Int,String,...,Boolean) = ("",0,"",..,true)

I can write a type alias

type MyType = (String,Int,String,...,Boolean)
val myTuple: MyType = ("",0,"",..,true)

Can I write this type alias dynamically? Is there a way to not be explicit in this type aliasing and let the compiler find the type itself to associate to the alias?

For exemple something like

case class MyCaseClass(x: String,y: Int,z:String,...,zz:Boolean)

type MyDynamicTupleType = MyCaseClass.tupled.parameter1.type

Not sure this is possible or if this is very useful, just find out that with very long tuples writing aliases is very boring and is just boilerplate (exemple here).

Open for macro-based or shapeless solutions

Community
  • 1
  • 1
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
  • 1
    I'm not exactly sure what you're asking. But you may find Shapeless useful for this. See https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0#generic-representation-of-sealed-families-of-case-classes – acjay Feb 09 '15 at 11:39
  • yes it seems so. Open to a shapeless exemple achieving this too :) – Sebastien Lorber Feb 09 '15 at 13:38
  • I don' t think you can do it at runtime ( Barring Shapeless ). But still you can try doing this with Scala Macros. – sarveshseri Feb 09 '15 at 14:21

1 Answers1

2

Combining a couple of pieces from shapeless gets us most of the way there - Generic to represent our case class as a HList, Tupler to represent the HList as a tuple:

sealed trait GenericAsTuple[G] {
  type Out
}
object GenericAsTuple {
  implicit def fromGenericAndTupler[G, T <: HList, O](
    implicit g: Generic[G]{type Repr = T}, t: Tupler[T] {type Out = O}) =
      new GenericAsTuple[G]{type Out = O}
  def apply[G](implicit g: GenericAsTuple[G]): GenericAsTuple[G]{
    type Out = g.Out} = g
}

val myGat = GenericAsTuple[MyCaseClass]
type MyDynamicTupleType = myGat.Out

I'm not aware of a way (short of macros) to avoid taking two steps to invoke - myGat needs to be a stable value to be able to declare a type alias, we can't just do GenericAsTuple[MyCaseClass].Out.

lmm
  • 17,386
  • 3
  • 26
  • 37