Private class escapes its defining scope

My code structure is as:

class A{

import A.B

@transient protected var x: B = null // this line gives compilation error
}

object A{

private final class B{…}
}

Compiling this code gives error as(comment shows the line):

private class B escapes its defining scope as part of type A.B

What causes this issue?

x is protected – any subclass can see it. It is of type B. But B is private, which subclasses are not allowed to see. That’s an illegal contradiction, so the compiler doesn’t let you do it.

As a general rule, the type of a value or method must always be visible anywhere that is allowed to see that value or method.

2 Likes

Since x is not private, it needs a type that is not private. You could, for example, define a trait that is type of x and extended by B.

1 Like

In mutable.LinkedHashMap.scala from standard scala library, LinkedEntry is defined as private class in companion object.

private[mutable] final class LinkedEntry[K, V](val key: K, var value: V)
extends HashEntry[K, LinkedEntry[K, V]] {
var earlier: LinkedEntry[K, V] = null
var later: LinkedEntry[K, V] = null
}

In LinkedHashMap.class:

private[mutable] type Entry = LinkedHashMap.LinkedEntry[K, V]
@transient protected var firstEntry: Entry = null
@transient protected var lastEntry: Entry = null

This code doesn’t give ‘escapes defining scope’ error. Shouldn’t that be the case?

private[mutable] access specifier does the trick.

Probably…
This is a question with a long history.