Skip to content

Instantly share code, notes, and snippets.

@lauris
Created August 9, 2014 10:12
  • Star 19 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lauris/7dc94fb29804449b1836 to your computer and use it in GitHub Desktop.
Convert case class to map in Scala
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))
@nilocoelhojunior
Copy link

Thanks!

@cricri777
Copy link

Really useful, thank you !!

@emhacker
Copy link

emhacker commented Dec 5, 2018

Kudos.

@wayfarerjing
Copy link

This is great

@manjunathswamy797
Copy link

Hi if i want to do reverse of it... Like i have a map of column names and datatypes creating a case class?

@mahmoudabbasi
Copy link

very useful
thanks

@riccardomerolla
Copy link

riccardomerolla commented Jul 4, 2020

def ccToMap(cc: AnyRef) = cc.getClass.getDeclaredFields.foldLeft (Map.empty[String, Any]) { (a, f) => f.setAccessible(true) a + (f.getName -> f.get(cc)) }

@klaeufer
Copy link

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