scala - Can I prevent "def" to be overriden with "val"? -
i have trait defines abstract method without parameters. want prevent implementors overriding val
, method called every time value needed. eg.
sealed trait downloader extends loader { def username: string def password: string def nonceprovider: nonceprovider def request: request def download = { val client = new client client execute request } }
this trait used downloading resources. write following bad implementation:
case class downloaderwithservicedefinition( override val username: string, override val password: string, override val nonceprovider: nonceprovider servicedefinition: servicedefinition) extends downloader { override val request = servicedefinitionrequest(servicedefinition, username, password, nonceprovider.generatenonce()) }
in implementation, request
assigned value during construction instead of behaving method, consecutive requests have same nonce value not intended. can prevent this?
you not want general language feature. assumption trait requires some valid implementation of request
of right type, , codes requirement. trait can make no assumptions/demands on implementation details of requirement.
as such, implementer has liberty use def, val, var or lazy val sees fit, greater knowledge trait has. , if correct implementation concerns you, burden of avoiding bugs indeed in implementation itself.
you can change definition def request(): request
or def request: () => request
make intent clearer , document contract need (actual java/scala doc helps).
it might request itself, if used way obtain nonce, should not in trait @ implementation detail. gather downloader
not have single request
@ all, make many needed, might have smell should structure oo design differently.
Comments
Post a Comment