Suppose I have the following trait and object:
trait NoAnon {
val i: Int
}
object NoAnon {
def create = new NoAnon {
val i = 123
}
}
I would like to prevent anonymous instances of NoAnon
from being created outside of the companion object. ie. only create
in this example should be allowed to do this. I can enclose these within another object, and make the trait private to that object to accomplish this:
object Ctx {
private[Ctx] trait NoAnon {
val i: Int
}
object NoAnon {
def create = new Ctx.NoAnon {
val i = 123
}
}
}
Is it possible to do this without the enclosing object Ctx
?
To be a little more clear, can traits mimic the functionality of a private abstract class constructor? That is, the following example, except with a trait.
abstract class NoAnon private[NoAnon] {
val i: Int
}
object NoAnon {
def create = new NoAnon {
val i = 123
}
}