0

I have a project based on ScalaJS and upickle. This means I do not have access to Scala reflection in my code on the JS side. I have a need to associate case class attributes with their names and am wondering if there is any way I can infer the name from the attribute.

So say I have the following code:

case class A(attr1: String, attr2: Int)

def foo[T, U](get: T => U, name: String) = { ... }

foo[A, String](_.attr1, "attr1")
foo[A, Int](_.attr2, "attr2")

I am wondering if there is a way I can define foo without needing to pass the actual name of the attribute?

ie something like

def foo[T,U](get: T => U) { // infer the name of the attribue ... }

Note that I have access to upickle's Reader and Writer objects for the given class so am wondering if there is a useful capability there?

user79074
  • 4,937
  • 5
  • 29
  • 57
  • I don't have time right now to write a full response, but you have essentially two ways: shapeless (using LabelledGeneric) or a macro. Since this is a rather syntactic problem, a macro would probably be a good fit. For an example very similar to yours, you can see this implementation: https://github.com/davegurnell/checklist/blob/develop/src/main/scala/checklist/RuleMacros.scala#L16 which provides a `field` macro that extracts the name from the attribute name. – Gabriele Petronella Apr 08 '17 at 13:55
  • @user79074 you can totally use *compile-time* reflection in Scala.js. So a macro would definitely work here. – gzm0 Apr 09 '17 at 19:46

0 Answers0