Last active
December 13, 2015 17:18
-
-
Save eamelink/4946357 to your computer and use it in GitHub Desktop.
Checking how constructor parameters do or do not end up as fields
This file contains hidden or 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
/* | |
* 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