list - NullPointerException on a listener pattern in scala -
i'm trying create listener design pattern that:
abstract class listener(g: engine) { g.addlistener(this) } class listener1(g: engine) extends listener(g) class listener2(g: engine) extends listener(g) class engine { val listener1 = new listener1(this) val listener2 = new listener2(this) var listeners: list[listener] = nil def addlistener(g: listener) = { listeners = g::listeners } }
but if fails nullpointerexception
, because listeners
equal null
when listener1
, listener2
created.
how overcome problem?
edit: tried following:
def addlistener(g: listener) = { if(listeners == null) { listeners = list(g) } else { listeners = g::listeners } }
but problem after class initialized, listeners = nil. need better design pattern achieve goal.
solution: without using lazy val or mutable collections:
var listeners: list[listener] = _ def addlistener(g: listener) = { if(listeners == null) listeners = list(g) else listeners = g::listeners }
using _
initialization instead of 'null' or 'nil' makes compiler not overwrite listeners
after listener1
, listener2
have been created.
with of lazy value , mutable collection:
class engine { val listener1 = new listener1(this) val listener2 = new listener2(this) lazy val listeners = collection.mutable.listbuffer.empty[listener] def addlistener(g: listener) { listeners += g } }
if badly need immutable list somewhere down road, turn buffer .tolist
method in callplace.