« Return to Thread: Companion object constructor visibility

Companion object constructor visibility

by Viktor Klang :: Rate this Message:

Reply to Author | View in Thread

Greetings Scalars,

Topic: Constructor visibility and companion object constructors

Given the following code, the 2.7.5 Scalac compiler tosses me a fine error: "constructor Name cannot be accessed in object ValueTypes1"

    object ValueTypes1
    {
        trait TypeDef[F,T <: TypeDef[F,T]]
        {
            val value : F
            override def toString = super.getClass.getSimpleName + "(" + value + ")"
        }

        abstract class TypeDefFactory[F,T <: TypeDef[F,T]](ctor : (F) => T, p : (F) => boolean)
        {
            def apply(f : F) : Option[T] = if(validate(f)) Some(ctor(f)) else None
            def unapply(t : T) : Option[F] = if(t eq null) None else Some(t.value)

            def validate(f : F) : boolean = p(f)
        }

        class Name private (val value : String) extends TypeDef[String,Name]

        object Name extends TypeDefFactory[String,Name]( new Name(_), !_.isEmpty ) // new Name(_) causes the error
    }


Now, since I cannot write: Some( new T(f) )  in the apply-method of the TypeDefFactory, I see no other solution than modify TypeDefFactory so the inheriting class/object has to define a "create" method as so:

        abstract class TypeDefFactory[F,T <: TypeDef[F,T]](p : (F) => boolean) // removed ctor : (F) => T,
        {
            def apply(f : F) : Option[T] = if(validate(f)) Some(ctor(f)) else None
            def unapply(t : T) : Option[F] = if(t eq null) None else Some(t.value)

            def validate(f : F) : boolean = p(f)
            def create(f : F) : T
        }

        class Name private (val value : String) extends TypeDef[String,Name]

        object Name extends TypeDefFactory[String,Name]( !_.isEmpty ) // removed new Name(_)
        {
           def create(s : String) = new Name(s)
        }

    }

However, this adds boilerplate, which I am very unfond of, so my question is:

Why is "new Name(_)" in the ValueTypes1 scope instead of the Name scope? Because the super-constructor call (TypeDefFactory((F) => T,(F) => boolean ) should _definately_ be in the scope of the inheriting class.
Or am I missing something?

Best regards,
--
Viktor Klang
Scala Loudmouth

 « Return to Thread: Companion object constructor visibility