Careeroza
Interfaces
Defining an Interface
An interface is a contract: a list of functions and properties a class promises to provide. Kotlin interfaces can also contain default implementations. They cannot store state (no backing fields).
Example
interface Clickable {
fun click() // abstract
fun showRipple() = println("Showing ripple") // default implementation
}
class Button(val label: String) : Clickable {
override fun click() = println("$label clicked")
}
fun main() {
val b = Button("Pay Now")
b.click()
b.showRipple()
}Output
Pay Now clicked Showing ripple
Properties in Interfaces
Example
An interface property is either abstract or has a getter; implementing classes provide the value.
interface Identifiable {
val id: String
val shortId: String get() = id.take(6) // computed from id
}
class Order(override val id: String, val amount: Int) : Identifiable
fun main() {
val o = Order("ORD20261012XYZ", 899)
println("${o.id} -> ${o.shortId}")
}Output
ORD20261012XYZ -> ORD202
Exercise
Exercise: Create an interface Discountable with val price: Double and a default function finalPrice(percent: Int). Implement it in Shoe.
Show answer
interface Discountable {
val price: Double
fun finalPrice(percent: Int) = price - price * percent / 100
}
class Shoe(override val price: Double) : Discountable
fun main() {
println(Shoe(2000.0).finalPrice(20)) // 1600.0
}