Part 09 / Topic 3 of 10
Interfaces: contracts, with some bodies included
An interface declares what a type can do, without carrying constructor state of its own. It can mix abstract members (no body — every implementer must supply one) with members that already have a default body, which every implementer gets for free unless it chooses to override it.
interface Notifier {
val channel: String
fun send(to: String, message: String): String
fun log(message: String) = println("[$channel] $message") // default body
}
class SmsNotifier(override val channel: String = "SMS") : Notifier {
override fun send(to: String, message: String): String {
log("sending to $to")
return "SMS to $to: $message"
}
}
A class can implement more than one interface — unlike open class inheritance, where
Kotlin allows only a single superclass:
class PaidSmsNotifier(private val perMessageInr: Double) : Notifier, Billable {
override val channel = "SMS-PAID"
override fun send(to: String, message: String): String { /* ... */ return "..." }
override fun chargeInr() = perMessageInr
}
[SMS] sending to 98xxxxxx01
SMS to 98xxxxxx01: Order #1042 shipped
[EMAIL] sending to 98xxxxxx01
Email to 98xxxxxx01: Order #1042 shipped
[SMS-PAID] sending paid SMS to 98xxxxxx01
Paid SMS to 98xxxxxx01: Order #1042 shipped
Billable notifiers: 1
Charge per message: ₹0.50
Is Notifier: true, is Billable: true
notifiers.filterIsInstance<Billable>() picks out only the objects that also implement
Billable from a List<Notifier> — a common pattern for "does this object also support X".
Full program: examples/02_interfaces.kt.
Done here? The practice set for Part 9 — including the solutions — is on the part page.