0

Let's say I have an

object Error{
    abstract class Reason{def p:P}
    case class A(p:P) extends Reason
    case class B(p:P) extends Reason
    ...
}

And that now I want to add a special case of B:

object Error{
    abstract class Reason{def p:P}
    case class A(p:P) extends Reason
    class B(val p:P) extends Reason{
        def apply(p:P) = new B(p)
        def unappply(b:B) = 
            if(b == null) None
            else Some(b.p)
    }

    case class SpecialB(override val p:P) extends B(p)
    ...
}

In this change, why must I declare parameter p in B as val and why didn't I have to when B was a case class?

User1291
  • 7,664
  • 8
  • 51
  • 108

2 Answers2

2

All parameters of a case class constructor are exposed as public values, which is not the case for a plain class, for which val must be used to make the parameter public.

cchantep
  • 9,118
  • 3
  • 30
  • 41
1

In a case class when you provide constructor parameter p, a field with public getter method with same signature as def p:P is created.

In a regular class you have to specify that parameter should have public methods via val or var. Otherwise it can be discarded after initialization. See Scala Constructor Parameters

Community
  • 1
  • 1
Tyth
  • 1,774
  • 1
  • 11
  • 17