mardi 21 avril 2015

Preventing the creation of anonymous classes from traits, without an enclosing object

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?

Aucun commentaire:

Enregistrer un commentaire