Skip to content

Instantly share code, notes, and snippets.

@elyphas
Created April 16, 2025 00:16
Show Gist options
  • Save elyphas/e78bf6d5f2f3ccf57eb5d817aa8ef822 to your computer and use it in GitHub Desktop.
Save elyphas/e78bf6d5f2f3ccf57eb5d817aa8ef822 to your computer and use it in GitHub Desktop.
import scala.deriving.Mirror
import jsonvalue.*
import scala.compiletime.{constValue, erasedValue}
case class Employee ( name: String, age: Int )
trait HelpersLabelledGeneric:
trait JsonEncoder[A]:
def encodeField(a: A): JsonValue
type Row = List[JsonValue]
trait RowEncoder[A]:
def encodeRow(a: A): Row
given JsonEncoder[Int] = JsonInt ( _ ) // when the trait has only one method.
given JsonEncoder[String] with
override def encodeField(a: String): JsonValue = JsonString(a)
given RowEncoder[EmptyTuple] with
override def encodeRow(a: EmptyTuple): Row = List.empty
given [H: JsonEncoder, T <: Tuple: RowEncoder]: RowEncoder[ H *: T] with
override def encodeRow(a: H *: T): Row =
summon[JsonEncoder[H]].encodeField(a.head) :: summon[RowEncoder[T]].encodeRow(a.tail)
/** * to get the field name */
inline def getElemLabels[A <: Tuple]: List[String] =
inline erasedValue[A] match {
case _: EmptyTuple => Nil
case _: (head *: tail) =>
val headElementLabel = constValue[head].toString
val tailElementLabels = getElemLabels[tail]
headElementLabel :: tailElementLabels
}
inline def getElemLabelsHelper[A](using m: Mirror.Of[A]) =
getElemLabels[m.MirroredElemLabels]
def tupleToCsv[X : RowEncoder](tuple: X): List[JsonValue] =
summon[RowEncoder[X]].encodeRow(tuple)
end HelpersLabelledGeneric
@main def hello(): Unit =
case class TestGrid ( look: String, amount: Int)
val helpersLabelledGeneric = new HelpersLabelledGeneric {}
val bob = Employee("Bob changos", 42)
trait Grid1[A]:
def loadValues(a: List[A]): Unit =
import helpersLabelledGeneric.given_RowEncoder_*:
import helpersLabelledGeneric.{given_JsonEncoder_String, given_RowEncoder_EmptyTuple, given_JsonEncoder_Int}
//val valores = helpersLabelledGeneric.tupleToCsv ( bob )
val valores = a.map( b => helpersLabelledGeneric.tupleToCsv ( b ) )
println(valores)
val fields = helpersLabelledGeneric.getElemLabelsHelper [ A ]
println ( fields )
end Grid1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment