scala - Why does the compiler complain when using the abstract modifier in a trait in two cases? -
i practicing chapter trait in online book programming in scala 1ed.
there 2 examples show power of traits, enrich thin interface , stackable modification. here snippet of implementation
// example 1 trait relation[t] { def compare(that: t): int def <(that: t) = compare(that) < 0 def >(that: t) = compare(that) > 0 def <=(that: t) = compare(that) <= 0 def >=(that: t) = compare(that) >= 0 } // example 2 trait doubling extends intqueue { abstract override def put(a: int) { super.put(a*2) } }
the above code fine compile.
i curious existence of abstract
modifier, first added abstract
modifier in front of relation::compare()
in example 1. maybe it's reasonable mark abstract
compare
going override subclass.
// case 1 abstract def compare(that: t): int
then compiler complains
error:(19, 16) `abstract' modifier can used classes; should omitted abstract members abstract def compare(that: t): int ^
i think message says should not put abstract
modifier in trait. try remove abstract
modifier doubling::put in example 2 this
// case 2 override def put(a: int) { super.put(a*2) }
but compiler complains
error:(35, 36) method put in class intqueue accessed super. may not abstract unless overridden member declared `abstract' , `override' override def put(a: int) { super.put(a*2) } ^
i know reason override
modifier here, don't know why compiler complains should add abstract
modifier it. compiler in previous case complains should put abstract in classes?
you "i think message says should not put abstract modifier in trait." no, means in scala mark class abstract if has abstract methods, don't use abstract
keyword on methods themselves. compiler knows method abstract because haven't provided implementation.
as second question, reason need abstract
keyword on override of put
intqueue
's put
abstract. telling compiler super.put(a*2)
not attempt call abstract method, of course not work -- expect trait mixed in provides implementation.
more info here.
Comments
Post a Comment