HelloCW
HelloCW

Reputation: 2255

Is it a good idea to place the code of instance a class in a interface in Kotlin?

The Code A is from the project android/architecture-components-samples.

The author place the code of instance a class DefaultServiceLocator in the interface ServiceLocator.

In my mind , normally a interface should not include any implement code.

Is it a good idea to place the code of instance a class in a interface in Kotlin?

Code A

interface ServiceLocator {
    companion object {
        private val LOCK = Any()
        private var instance: ServiceLocator? = null


        fun instance(context: Context): ServiceLocator {
            synchronized(LOCK) {
                if (instance == null) {
                    instance = DefaultServiceLocator(
                            app = context.applicationContext as Application,
                            useInMemoryDb = false)
                }
                return instance!!
            }
        }

        /**
         * Allows tests to replace the default implementations.
         */
        @VisibleForTesting
        fun swap(locator: ServiceLocator) {
            instance = locator
        }
    }

    ...
}


open class DefaultServiceLocator(val app: Application, val useInMemoryDb: Boolean) : ServiceLocator {
  ...
}

Upvotes: 0

Views: 146

Answers (2)

Raymond Arteaga
Raymond Arteaga

Reputation: 4673

As per kotlin interfaces documentation:

Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store state. They can have properties but these need to be abstract or to provide accessor implementations.

So... there's no problem in using method implementations on the interfaces. That feature might offer you extra power (if you like and need to use it).

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

In my mind , normally a interface should not include any implement code.

Welcome back from hibernation ;) Yes, you could achieve the same with interface + abstract class but you can have default implementation also as part of the interface for some time now in many languages. Which way you go is up to you, but if you have only one abstract class implementing your interface then it is often handy to be able to merge this into one file for sake of ease of future maintenance.

Upvotes: 1

Related Questions