Skip to content

Instantly share code, notes, and snippets.

@gnapse
Last active March 7, 2017 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnapse/96387a056f0cf45dac7a to your computer and use it in GitHub Desktop.
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
// 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
}
}
@mailursubbu
Copy link

mailursubbu commented Mar 7, 2017

def output(str: Any): Unit = {
// The class parameter fake is accessible beyond the construction phase
if (!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 :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment