Skip to content

Instantly share code, notes, and snippets.

@frgomes
Created October 29, 2022 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frgomes/fa6ecbefb16ce654e9c2793f817eac1d to your computer and use it in GitHub Desktop.
Save frgomes/fa6ecbefb16ce654e9c2793f817eac1d to your computer and use it in GitHub Desktop.
Scala - obtain field names and field types from case class employing TypeTag
import scala.reflect.runtime.universe.TypeTag
implicit class ProductExtension[T <: Product : TypeTag](o: T) {
def productElementNames: Iterator[String] = {
import scala.reflect.runtime.universe._
typeOf[T].members
.collect { case m: MethodSymbol if m.isCaseAccessor => m.name.toString }
.toList.reverse.toIterator
}
def productElementTypeNames: Iterator[String] = {
import scala.reflect.runtime.universe._
typeOf[T].members
.collect { case m: MethodSymbol if m.isCaseAccessor => m.returnType.toString }
.toList.reverse.toIterator
}
}
@frgomes
Copy link
Author

frgomes commented Oct 29, 2022

  test("ability to obtain list of field names from a case class") {
    val o = Explorer(id = 1, firstname = "Arne", lastname = "Saknussem", cartoon = Some("Journey to the Center of The Earth"))
    val names = o.productElementNames
    assertEquals(names.toList, List("id", "firstname", "lastname", "cartoon"))
  }

  test("ability to obtain list of field type names from a case class") {
    val o = Explorer(id = 1, firstname = "Arne", lastname = "Saknussem", cartoon = Some("Journey to the Center of The Earth"))
    val types = o.productElementTypeNames
    assertEquals(types.toList, List("Int", "String", "String", "Option[String]"))
  }

  case class Explorer(id: Int, firstname: String, lastname: String, cartoon: Option[String])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment