Last active
March 7, 2017 15:04
-
-
Save gnapse/96387a056f0cf45dac7a to your computer and use it in GitHub Desktop.
Testing if it's possible to have Scala class parameters not becoming instance attributes
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
// Regarding these discussions about Scala class constructor parameters: | |
// http://stackoverflow.com/questions/15639078/scala-class-constructor-parameters | |
// http://stackoverflow.com/questions/1889454/in-scala-how-do-you-define-a-local-parameter-in-the-primary-constructor-of-a-cl | |
// Class parameter `fake` is not prefixed by either `val` or `var` | |
class Testing(fake: Boolean) { | |
val buffer = if (fake) null else new StringBuilder() | |
def output(str: Any): Unit = { | |
// The class parameter `fake` is accessible beyond the construction phase | |
if (!fake) { | |
buffer.append(str.toString) | |
} | |
} | |
override def toString: String = { | |
// We're accessing it here in the `toString` method as well | |
if (fake) "()" else s"(${buffer.toString()})" | |
} | |
} | |
// Entry point just to make this example runnable | |
object Testing { | |
def main (args: Array[String]): Unit = { | |
println(test(new Testing(fake = true))) | |
println(test(new Testing(fake = false))) | |
} | |
private def test(instance: Testing): String = { | |
instance.output("Hello World") | |
instance.toString | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
def output(str: Any): Unit = {
// The class parameter
fake
is accessible beyond the construction phaseif (!fake) {
buffer.append(str.toString)
}
}
My guess : Scala may be feeding "fake" arg to "output" function using "Partially applied functions and currying"
PS: I cant update stackoverflow as I dont have 50 pts yet :)