Scala implementation of mutable stack throwing exception -
here mutable implementation of stack :
class linkedstackgeneric { var first : nodegeneric = _ def isempty : boolean = { first == null } def push(itemname : any) = { val oldfirst = first first = new nodegeneric(itemname , oldfirst) } def pop = { first = first.next first.itemname } } class nodegeneric(val itemname : , val next : nodegeneric) {} println("*********** testing linkedstackgeneric *****************") val generic = new linkedstackgeneric generic.push("test") generic.push("here"); println(generic.isempty) println(generic.pop); println(generic.isempty) println(generic.pop); println(generic.isempty) when run code produces following :
*********** testing linkedstackgeneric ***************** false test false exception in thread "main" java.lang.nullpointerexception @ linkedstackgeneric.pop(linkedstackgeneric.scala:19) @ stacksandqueuestest$.main(stacksandqueuestest.scala:37) @ stacksandqueuestest.main(stacksandqueuestest.scala) this line causes error :
println(generic.pop); what causing exception, not pushing items onto stack correctly ? since push 2 items :
generic.push("test") generic.push("here"); shouldn't exception not thrown ?
fix pop method. order of execution causing issue...
def pop = { val ret = first.itemname first = first.next ret }
Comments
Post a Comment