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 the creation of anonymous instances NoAnon

outside of the companion object. i.e. create

this example alone should be allowed to do so. I can wrap them in another object and make a property private to that object, do the following:

object Ctx {

    private[Ctx] trait NoAnon {
        val i: Int
    }

    object NoAnon {
        def create = new Ctx.NoAnon {
            val i = 123
        }
    }

}

      

Can I do this without an enclosing object Ctx

?

To be more clear, can traits mimic the functionality of the private constructor of abstract classes? That is, the next example, except with a sign.

abstract class NoAnon private[NoAnon] {
    val i: Int
}

object NoAnon {
    def create = new NoAnon {
        val i = 123
    }
}

      

+3


source to share


1 answer


Perhaps you could use a class with a private constructor and extend it with your trait. You can even nest this class in a companion object:

trait NoAnon extends NoAnon.type#NoAnonCheck { 
    val i: Int
}

object NoAnon {
    class NoAnonCheck private[NoAnon]
    def create = new NoAnon { 
        val i = 1 
    }   
}

      

Then if you tried:

new NoAnon { val i = 2 }

      



You get:

error: constructor NoAnonCheck in class NoAnonCheck cannot be accessed in <$anon: NoAnonCheck with NoAnon>

      

But you can use NoAnon.create

. Other than adding something like this, I don't think there is currently a clean way to do this in Scala.

Of course, as you know, and as mentioned in the comments, the other options are to make the property private in the scope of the enclosing object or package.

+2


source







All Articles