Interfaces

If you have any experience with any modern language, then you have probably used a type that defines a behavior. These types are called traits in Scala, protocols in Swift, and interfaces in Kotlin, Java, and C#.

An interface is a blueprint or a definition of a type. When a type implements an interface, we can then refer to it by this contract, that is, a set of methods that the type implements.

Here is an interface declaration in Kotlin:

interface Drivable {
fun drive()
}

The syntax for implementing an interface is the same as for inheritance. In the implementing class header, after a primary constructor or a class name comes the colon and the interface name:

class Car : Drivable {
override fun drive() {
println("Driving a car")
}
}

The only difference from inheritance syntax is that we don't call the base type constructor because interfaces don't have one.

The implementing type (unless it is an abstract class) has to implement or override all the members that interface defined. Otherwise, you'd get a compiler error.

Interfaces in Kotlin, the same as in Java (since Java 8), can have default method implementations. Consider this interface:

interface Flyable {
fun climb() {
println("Climbing")
}

fun fly()
}

Now, all the implementing classes only have to override the function, without the default implementation:

class AirPlane : Flyable {
override fun fly() {
println("Flying a plane")
}
}

But if you wish, you can also override the function that has a default implementation:

class Drone : Flyable {
override fun climb() {
println("Climbing slowly")
}

override fun fly() {
println("Flying a plane")
}
}

You can also define a property inside an interface in Kotlin, as this example shows:

interface Ridable {
fun ride()
val name: String
}

Finally, we have to mention that visibility modifiers that can be applied to classes can also be applied to an interface. But, interface members cannot have private or protected visibility modifiers. They can only have public (which is default) and internal.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.203.96