Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend a singleton (object declaration) in Kotlin?

I have an object declaration (object A : BaseClass) and I want to create another object declaration B that inherits from A's implicit class. BaseClass is a class and not an interface. Is it possible in Kotlin?

like image 438
SpaceBison Avatar asked Jul 20 '18 06:07

SpaceBison


People also ask

Can we extend object in Kotlin?

Kotlin provides the ability to extend a class or an interface with new functionality without having to inherit from the class or use design patterns such as Decorator. This is done via special declarations called extensions.

How do I extend my Kotlin?

In Kotlin we use a single colon character ( : ) instead of the Java extends keyword to extend a class or implement an interface. We can then create an object of type Programmer and call methods on it—either in its own class or the superclass (base class).

Which is the proper way to declare a singleton named class in Kotlin?

In Kotlin, we need to use the object keyword to use Singleton class. The object class can have functions, properties, and the init method. The constructor method is not allowed in an object so we can use the init method if some initialization is required and the object can be defined inside a class.

Is singleton thread-safe Kotlin?

Deal with multiple threads(singleton thread safe)a Kotlin object actually relies on a Java static initialization block. t enables thread-safe lazy initialization without having to rely on a locking algorithm like the complex double-checked locking.


1 Answers

You can use delegation. Note that you can only delegate via interface, so you'll need to create an interface with subset of methods you need to delegate through.

interface Iface {
   fun doStuff()
}

object BaseObject: Iface {
   override fun doStuff() { }
}

class BaseClass: Iface {
   override fun doStuff() { }
}

object ExtendedObjectDelegatingToObject: Iface by BaseObject {
   fun doSomethingElse() { }
}

object ExtendedObjectDelegatingToClass: Iface by BaseClass() {
   fun doSomethingElse() { }
}

class ExtendedClassDelegatingToObject: Iface by BaseObject {
   fun doSomethingElse() { }
}

class ExtendedClassDelegatingToClass: Iface by BaseClass() {
   fun doSomethingElse() { }
}

fun example() {
    BaseObject.doStuff() // can call doStuff from BaseObject
    ExtendedObjectDelegatingToObject.doStuff() // can call doStuff from ExtendedObject
    ExtendedObjectDelegatingToObject.doSomethingElse() // can also call additional methods on ExtendedObject
}
like image 119
SimY4 Avatar answered Sep 28 '22 02:09

SimY4