0

I'd like to have some type 'ValidatedVals' that can be instantiated exclusively by a single class (i.e. it is the single factory for ValidatedVals).

I'd then like to reference this ValidatedVals type in many other classes.

Private constructors seems like one answer... but ...

The code below fails because (apparently) an inner class with a private constructor, declared within

object X{  ... }

makes that constructor not visible within object X

So, in the code below, how can I make it so that:

  • ONLY ValidatedValsFactory can construct a ValidatedVals object
  • AND I can reference a ValidatedVals type in other classes?

_

class ValidatedValsFactory {}

object ValidatedValsFactory {

  class ValidatedVals private (val a: Int, val b: Int) {}

  def validate(a: Int, b: Int): Unit = { /* .... */ }

  def makeValidated(a: Int, b: Int): ValidatedVals = {
    validate(a, b);
    // **** Nope. Fail. Not visible. *****
    return new ValidatedVals(a, b)
  }
}

class ValidatedValsConsumer {
  def f(param: ValidatedValsFactory.ValidatedVals): Unit = { /* ... */ }
}
  • I don't want f's parameter's type to be an interface (because its easy to circumvent the validate by implementing the interface).
  • I can't move class ValidatedVals into the class definition of ValidatedValsFactory because ValidatedValsConsumer needs to be able to reference the inner class typename (and therefore ValidatedVals must be a static declaration).

garrghh!

user48956
  • 14,850
  • 19
  • 93
  • 154

2 Answers2

2

Looks like the compilation error goes away if you make it private to the object:

class ValidatedVals private[ValidatedValsFactory] (val a: Int, val b: Int) {}
dhg
  • 52,383
  • 8
  • 123
  • 144
1

Consider declaring your ValidatedVals type as a sealed class or trait. More details here: What is a sealed trait?

Community
  • 1
  • 1
Daryl Odnert
  • 522
  • 3
  • 15