How do I declare a constructor for an 'object' class type in Scala? I.e., a one time operation for the singleton -
i know objects treated pretty singletons in scala. however, have been unable find elegant way specify default behavior on initial instantiation. can accomplish putting code body of object declaration seems overly hacky. using apply doesn't work because can called multiple times , doesn't make sense use case.
any ideas on how this?
classes , objects both run code in body upon instantiation, design. why "hacky"? it's how language supposed work. if braces, can use them (and they'll keep local variables being preserved , world-viewable).
object initialized { // initalization block { val somestrings = list("a","be","sea") somestrings.filter(_.contains('e')).foreach(s => println("contains e: " + s)) } def dosomething { println("i initialized before saw this.") } } scala> initialized.dosomething contains e: contains e: sea initialized before saw this. scala> initialized.somestrings <console>:9: error: value somestrings not member of object initialized initialized.somestrings
Comments
Post a Comment