Scala passing method to supers constructor -
i'd have hierarchy base class can take function in constructor , derived class can supply method function. there 1 way below it's ugly. have declare child's function in constructor arg list of super's constructor. means function anonymous , not method of child class (though don't think care that). real code long , end difficult read, if had more 1 of these functions.
thus:
class a[t](s1: string, s2: string, w: (string, string) => unit){ def go: unit = { w(s1, s2) } } val externalwriter = { (s1: string, s2: string) => println (s1+s2) } val w1 = new a[string]("hello ", "world", externalwriter) w1.go case class b(s1: string, s2: string) extends a[string](s1, s2, w = { (a: string, b: string) => println ("class b:"+a+b) }){ def write: unit = go } val w2 = b("hey ","guys") w2.write
w1.go prints "hello world" , w2.write prints "class b: hey guys". want there way have w
method or val of class b , still pass super's constructor?
i similar monkjack's solution, using more of mixin pattern. key difference here being i'm using anonymous refinement of a
create w1
, allowing me keep w
method.
abstract class a(s1: string, s2: string) { def w(arg1: string, arg2: string): unit def go(): unit = { w(s1, s2) } } val w1 = new a("hello", "world") { def w(a: string, b: string): unit = println(a + b) } w1.go() case class b(s1: string, s2: string) extends a(s1, s2) { def w(a: string, b: string): unit = println("class b:" + + b) def write: unit = go } val w2 = b("hey ", "guys") w2.write trait c { def w(a: string, b: string): unit = println("trait c:" + + b) } val w3 = new a("bye ", "everyone") c w3.go()
Comments
Post a Comment