Kotlin Interfaces
In Kotlin, just like in many other object-oriented programming languages, an interface is a type that contains declarations of abstract methods but does not contain any state or implementation of the methods. An interface can be implemented by any class, in order to use the methods declared in the interface.
Defining an Interface in Kotlin
In Kotlin, an interface is defined by using the interface
keyword. Here is a simple example:
interface MyInterface {
fun printMessage()
fun printMessageLine()
}
In the above example, MyInterface
is an interface that contains two methods: printMessage()
and printMessageLine()
. These methods are abstract by default, which means they have no body and must be overridden in the classes that implement this interface.
Implementing an Interface
To implement an interface in a class, you use the :
operator and then provide the implementations of the abstract methods. Let's implement the MyInterface
in a class called InterfaceImp
:
class InterfaceImp : MyInterface {
override fun printMessage() {
println("This is a message.")
}
override fun printMessageLine() {
println("This is a message line.")
}
}
In the above example, InterfaceImp
class is implementing the MyInterface
and providing the implementation details for the printMessage()
and printMessageLine()
methods.
Properties in Interfaces
In Kotlin, you can also declare properties in an interface. However, keep in mind that these properties need to be abstract or provide accessor implementations. Here is an example:
interface MyInterface {
var myVar: Int // abstract property
fun myMethod(str: String) // abstract method
fun printMessage() { // method with default implementation
println("This is a message from the Interface.")
}
}
In the above example, myVar
is an abstract property that must be overridden in the implementing class, and printMessage()
is a method with a default implementation.
Overriding a Member of an Interface
When you implement an interface, you can also override the members of the interface. Here's an example:
interface MyInterface {
val prop: Int // abstract property
fun foo() {
print(prop)
}
}
class Child : MyInterface {
override val prop: Int = 29
}
In the above code, Child
class is implementing the MyInterface
and providing the implementation for the property prop
.
Conclusion
In Kotlin, interfaces are a central part of object-oriented programming. They allow you to define a contract for classes, without specifying the implementation details. This can be especially useful when you want to ensure that a class meets a certain standard, or when you want to separate the specification of a task from the implementation.