简体   繁体   中英

Protected Inner class constructor in Scala

I'm not sure why this won't compile - I'm trying to use an inner class (or trait) such that other objects can work with the resulting "RequestReturn", but only Trait Request and it's descendants can construct the object in the first place. I may be taking the wrong approach but shouldn't this code logically work? I've flagged the RequestReturn constructor as protected[Request] so it stands to reason that class RequestContinue would have the ability to call the constructor also.

trait Request {

  class RequestReturn protected[Request](val x:Any)

  def fulfill(item:Boolean):RequestReturn = new RequestReturn(item) //this line compiles
}

trait RequestContinue extends Request{


  override def fulfill(item:Boolean):RequestReturn = new RequestReturn(item) //this won't compile

}

Error:(19, 54) constructor RequestReturn in class RequestReturn cannot be accessed in trait RequestContinue Access to protected constructor RequestReturn not permitted because enclosing trait RequestContinue in package .... is not a subclass of class RequestReturn in trait Request where target is defined override def fulfill(item:Boolean):RequestReturn = new RequestReturn(item) ^

The rules are here :

Access from RequestReturn, descendants and their companion modules; and from Request and its companion module.

You could define a protected factory method in Request for your use case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM