Tuesday, 15 May 2012

scala - Use a stored value in the superclass' constructor when extending a class taking a by-name parameter -



scala - Use a stored value in the superclass' constructor when extending a class taking a by-name parameter -

i have case wish extend class takes by-name parameter in it's constructor:

class extension(something: something) extends base(something.dosomething(something.getsomething(false)) class base(expression: => result) { ... }

however, phone call something.getsomething(false) causes side-effects, , can't called multiple times.

how can store result of something.getsomething(false), before passing superclass' constructor?

we can having 2 constructors - 1 takes both parameter , generated parameter, , 1 takes parameter user should provide.

we create first constructor private, people don't accidentally utilize it, utilize sec constructor build value , pass first.

class="lang-scala prettyprint-override">class extension private (something: something, generatedfromsomething: generated) extends base(something.dosomething(generatedfromsomething) { def this(something: something) = this(something, something.getsomething(false)) }

as erikallik suggests in comments, may best avoid inheritance if possible, becomes trivial outside of case:

def extended(something: something) = { val generatedfromsomething = something.getsomething(false) new base(something.dosomething(generatedfromsomething) }

scala pass-by-name

No comments:

Post a Comment