Created
August 9, 2014 10:12
-
-
Save lauris/7dc94fb29804449b1836 to your computer and use it in GitHub Desktop.
Convert case class to map in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ccToMap(cc: AnyRef) = | |
(Map[String, Any]() /: cc.getClass.getDeclaredFields) { | |
(a, f) => | |
f.setAccessible(true) | |
a + (f.getName -> f.get(cc)) | |
} | |
// Usage | |
case class Column(name: String, | |
typeCode: Int, | |
typeName: String, | |
size: Int = 0) | |
val column = Column("id", 0, "INT", 11) | |
println(ccToMap(column)) |
Really useful, thank you !!
Kudos.
This is great
Hi if i want to do reverse of it... Like i have a map of column names and datatypes creating a case class?
very useful
thanks
def ccToMap(cc: AnyRef) = cc.getClass.getDeclaredFields.foldLeft (Map.empty[String, Any]) { (a, f) => f.setAccessible(true) a + (f.getName -> f.get(cc)) }
def productToMap(cc: Product) = cc.productElementNames.zip(cc.productIterator).toMap
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!