Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Feb 16, 2017

Thanks!

@cricri777

This comment has been minimized.

Copy link

commented Oct 24, 2018

Really useful, thank you !!

@emhacker

This comment has been minimized.

Copy link

commented Dec 5, 2018

Kudos.

@wayfarerjing

This comment has been minimized.

Copy link

commented Mar 26, 2019

This is great

@manjunathswamy797

This comment has been minimized.

Copy link

commented Apr 9, 2019

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

@mahmoudabbasi

This comment has been minimized.

Copy link

commented May 26, 2019

very useful
thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.