3

I am reading the example 5.2.2 from http://www.scala-lang.org/docu/files/ScalaReference.pdf ==>

Example 5.2.2

A useful idiom to prevent clients of a class from constructing new instances of that class is to declare the class abstract and sealed :

   object
    m {
    abstract sealed class
    C (x: Int) {
          def nextC = new C(x + 1) {} } val= empty = new C(0) {} 
}

For instance, in the code above clients can create instances of class m.C only by call- ing the nextC method of an existing m.C object; it is not possible for clients to create objects of class m.C directly. Indeed the following two lines are both in error:

new m.C(0)    **** error: C is abstract, so it cannot be instantiated.

new m.C(0) {}  ****error: illegal inheritance from sealed class.

====

I cant understand how inheritance is declared !! Thanks

SaKou
  • 259
  • 1
  • 13

1 Answers1

2

You can inherit from a sealed class only from the same file. However, you can use that type anywhere in your program.

This is instantiation attempt: new m.C(0), and it's not allowed because the class is abstract. You have to provide an implementation, i.e. at least an empty constructor body: {}.

However, once you try to do that with new m.C(0) {} you are actually creating a new anonymous class which is a subtype of A, which is also not allowed from outside (another file), hence the error. That's where you see the inheritance error.

Compare these ways to instantiate a class:

scala> class A
defined class A

scala> new A
res0: A = A@3fbfbd15

scala> new A {}
res1: A = $anon$1@bd978db

scala> new {} with A
res2: A = A@342fe5cf

scala> res1.getClass
res3: Class[_ <: A] = class $anon$1

scala> res2.getClass
res4: Class[_ <: A] = class A

scala> res0.getClass
res5: Class[_ <: A] = class A

scala> val a: A = res1
a: A = $anon$1@bd978db

Notice the type of res1 compared to other resX - it's anonymous, but it does extend A and can be used in place of A.

yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65
  • why did you used the with keyword here ? can we use it with class too ?? cause I know that it is reserved for trait ! @Aleksey – SaKou Feb 01 '16 at 10:20
  • I just wanted to show various ways to instantiate the class, but for the purpose of this answer `with` is not required. – yǝsʞǝla Feb 01 '16 at 22:59