nicolaosc
nicolaosc

Reputation: 11

Scala: Typesafe macro to extract value of case class field

We have been banging our heads for a while on this but we cannot find a solution. In our project we would like to write some DSL to migrate some old code in our codebase.

We would like to make a macro that given an instance of a case class gives us the possibility to extract the value in a typesafe manner. In this case it should be possible to declare x of type Int.

case class MyPersonalCaseClass(token: Int, str: String)

val someVariable = MyPersonalCaseClass(123, "SOMESTRING")
val x = Macros.->(someVariable, "token")

Here “token” is a compile-time constant, referring to the field name. The macro can be declared with something like

def ->[T](value:T,key: String): Any = macro MacrosImpl.arrow[T]

As for our understanding the only way was with whitebox macros, feel free to change the signatures.

def arrow[T: c.WeakTypeTag](c: whitebox.Context)(value: c.Expr[T], key:c.Expr[String]): c.Expr[Any] = 
{
  import c.universe._
  val caseClassType: c.universe.Type = weakTypeOf[T]
  ???
}

Scala version is “2.12.8”.

The reason we need something like this is we are porting a lot of code from perl and we would like to give the programmers a vagueish idea they are still writing it.

thanks in advance!

Upvotes: 1

Views: 206

Answers (1)

Dmytro Mitin
Dmytro Mitin

Reputation: 51648

Try

import shapeless.LabelledGeneric
import shapeless.record._
LabelledGeneric[MyPersonalCaseClass].to(someVariable).get(Symbol("token")) // 123

Upvotes: 1

Related Questions