Skip to content

Instantly share code, notes, and snippets.

@xerial
Created October 8, 2017 16:32
Show Gist options
  • Save xerial/370e4b2e5e8caf4cdc0311df9ce0c486 to your computer and use it in GitHub Desktop.
Save xerial/370e4b2e5e8caf4cdc0311df9ce0c486 to your computer and use it in GitHub Desktop.
Using Surface to convert objects into Map
import wvlet.surface
import wvlet.surface.Surface
import scala.reflect.runtime.{universe => ru}
class MapConverter[A](surface: Surface) {
def toMap(a: A): Map[String, Any] = {
val m = Map.newBuilder[String, Any]
for (p <- surface.params) {
m += (p.name -> p.get(a))
}
m.result()
}
}
object MapConverter {
def of[A: ru.TypeTag]: MapConverter[A] = new MapConverter(surface.of[A])
def toMap[A: ru.TypeTag](a: A): Map[String, Any] = {
MapConverter.of[A].toMap(a)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment