scala - Calling a trait's superclass method from an unrelated object -
at present have dozens of traits contain following method:
trait thistrait extends supertrait { override def getlist: list[string] = list(/* invariant list of strings */) ::: super.getlist }
where "invariant" means each instance of mytrait
has same base list, likewise each instance of supertrait
has same base list, etc. it's wasteful recompute every time method called, , i'd change of these following
trait thistrait extends supertrait { override def getlist: list[string] = getlist.getlist(super.getlist) } // see edit below modified version of htis private object getlist { private val baselist = (/* invariant list of strings */) private var thislist = null def getlist(superlist: list[string]) = { if(thislist == null) thislist = baselist ::: superlist thislist } }
which isn't too awful since super.getlist
returning (mostly) precomputed list, i'd prefer if following
private object getlist { private val thislist = (/* invariant list of strings */) ::: mytrait.super.getlist def getlist = thislist }
i via mytrait.getclass.getsuperclass.getmethod("getlist")
, hoping there type-safe way of doing (besides hard-coding reference supertrait
's getlist
object)
edit: improve via
private object getlist { private val baselist = (/* invariant list of strings */) private var thislist = null def getlist(superlist: => list[string]) = { if(thislist == null) thislist = baselist ::: superlist thislist } }
so won't call super.getlist
unless it's needed, i'm still interested in knowing if there's type-safe way of doing mytrait.super.getlist
no, , it's thing. if possible, break class invariants in many cases. pretty sure if call method via reflection, you'll same implementation calling mytrait
's getlist
, , infinite loop.
Comments
Post a Comment