1
interface SomeInterface {
        fun someFunction()
}

class SomeClass(private val someInterface: SomeInterface) {

}

What does it mean? As far as I know, interface can't instantiate objects and if it can then where should I implement someFunction()?

Md. Yamin Mollah
  • 1,609
  • 13
  • 26
  • 1
    `someInterface` val needs to be of a class which implements `SomeInterface`. This means you need to implement the interface and use its object as a parameter – Mangat Rai Modi May 08 '20 at 14:51
  • `someInterface` holds an instance of implementation of that interface. Just like if you allow `Any` to be a parameter, you can receive `String`, `Int`, ... everything. Because they are an implementation (actually extension because Any is class, but you can relate) of Any. – Animesh Sahu May 08 '20 at 14:58
  • Related questions: [What does it mean to “program to an interface”?](https://stackoverflow.com/questions/383947/) and [What is polymorphism, what is it for, and how is it used?](https://stackoverflow.com/questions/1031273/). – Slaw May 08 '20 at 15:39

1 Answers1

4

You are correct that you cannot instantiate SomeInterface directly, but you can pass implementations of your interface to SomeClass. This way SomeClass can use someFunction() but doesn't care about the lower-level implementation details of the interface (aka polymorphism).

interface SomeInterface {
    fun someFunction()
}

class SomeClass(private val someInterface: SomeInterface) {
    fun doSomething() = someInterface.someFunction()
}

class SomeImplementation(): SomeInterface {
    override fun someFunction() {
        println("did something")
    }
}

fun main() {
    val someClass = SomeClass(SomeImplementation())
    someClass.doSomething()
}
Rjbcc58
  • 176
  • 2
  • 14