Reputation: 42260
In Kotlin we can modify a class with the sealed
modifier to denote that the class can only be extended within the same module; or from the docs:
Sealed classes and interfaces represent restricted class hierarchies that provide more control over inheritance. All subclasses of a sealed class are known at compile time. No other subclasses may appear after a module with the sealed class is compiled. For example, third-party clients can't extend your sealed class in their code. Thus, each instance of a sealed class has a type from a limited set that is known when this class is compiled.
What I want to know is, can the same or similar behaviour be applied to class members; for example, consider the following code. All of the classes and interfaces exist in the same module:
// I don't want to seal this because it should be implementable beyond this module.
interface Hashable {
val hash: Hash
}
// I don't want to seal this because it should be extensible beyond this module.
abstract class Base : Hashable {
final override val hash: Hash get() = hashOf(...)
}
open class Derived : Base {
// This doesn't work because it's final in the base class.
final override val hash: Hash get() = hashOf(...)
}
What I essentially want to express is, "I (the developer) determine how a Base
should create it's hash, until I (the developer) state otherwise in a derived class. Nobody else outside of this module has the ability to alter how each extension or derivative of Base
may create its hash."
Is this possible?
Upvotes: 0
Views: 645
Reputation: 28332
You can create additional property with internal
visibility:
abstract class Base : Hashable {
final override val hash: Hash get() = _hash
internal open val _hash: Hash get() = hashOf(...)
}
open class Derived : Base() {
override val _hash: Hash get() = hashOf(...)
}
Upvotes: 1