Skip to content

Instantly share code, notes, and snippets.

@eamelink
Last active December 13, 2015 17:18
Show Gist options
  • Save eamelink/4946357 to your computer and use it in GitHub Desktop.
Save eamelink/4946357 to your computer and use it in GitHub Desktop.
Checking how constructor parameters do or do not end up as fields
/*
* bar is not a real field: after the lazy val bork is initialized,
* 'bar' is set to null.
*
* It's a normal field when we make bork a def, add 'val' or 'var' to bar or make it a case class.
* It's not a field at all when we make bork a val.
*/
class MyClass(param: String) {
lazy val field = param
}
object Runner extends App {
def printFields(o: Any) = {
val fields = o.getClass.getDeclaredFields
val keyValuePairs = fields map { field =>
field.setAccessible(true)
println("%10s -> %s" format (field.getName, field.get(o)))
}
}
val foo = new MyClass("content")
println("Before touching field:")
printFields(foo)
foo.field
println("After touching field:")
printFields(foo)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment