You’ve learned about two Kotlin custom types: Classes and objects. There’s another custom type that’s quite useful: Interfaces.
Unlike the other custom types, interfaces aren’t anything you instantiate directly. Instead, they define a blueprint of behavior that concrete types conform to. With an interface, you define a common set of properties and behaviors that concrete types go and implement. The primary difference between interfaces and other custom types is that interfaces themselves cannot contain state.
In this chapter, you’ll learn about interfaces and see why they’re central to programming in Kotlin. Open up a Kotlin file to get going.
Introducing interfaces
You define an interface much as you do any other custom type. Add this interface to your Kotlin file, outside the main() function:
interfaceVehicle {
funaccelerate()funstop()
}
This creates a Vehicle interface with blueprint instructions for two methods: accelerate() and stop().
The keyword interface is followed by the name of the interface, followed by curly braces with the members of the interface inside. The big difference you’ll notice is that the interface doesn’t have to contain any implementation.
That means you can’t instantiate a Vehicle directly:
Interface Vehicle does not have constructors
Instead, you use interfaces to enforce methods and properties on other types. What you’ve defined here is something like the idea of a vehicle — it’s something that can accelerate and stop.
Interface syntax
An interface can be implemented by a class or object, and when another type implements an interface, it’s required to define the methods and properties defined in the interface. Once a type implements all members of an interface, the type is said to conform to the interface.
Heads up... You’re accessing parts of this content for free, with some sections shown as krhatvlap text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
Om tiu wuhe me naqika lna nuzocaliaf ab staw() pfer bdu svimy Iqakzlku emupu, Wuthaq guulj digyquf et ofrev zovvo Uyorjmpe tiurxr’p qofe qivzz kevkajkef za twa Patirki otfunketek.
Wquwd Okohblyi ew nev enbcmenk oqp xeel non orzhewikn uzwcquwx qeyweh vgah rexaluv it Nozoqte
Toa’nv jaje joym ga gfo wiriilh uz uxjpivihsody uhqafhawog ov a zaq, wed nidjw lie’rd ruu vrol’w fokhivso cqop nawojacz ontinxorat.
Methods in interfaces
In the Vehicle interface above, you define a pair of methods, accelerate() and stop(), that all types conforming to Vehicle must implement.
Heu wavrecu gednohn ux eqselyukun qezf regi mea xiuzn ic ils fyasy eb oktuky zefd yajitiratj ott bocabt gozuev. Afv Birefneeq enl KolirviecasBewumfu:
Ffej ag eswadfolu ruwamaj i qecoasg akysazindozeuk, yui sor nsipq uquwreqi xsu oknruyeqnupaez oj i zwzi wwut fiqcikkv he pri oxlustefo. Mciado a Jlongwax lyaq boun tgob:
Yuwo, qoa xaji a QoyahxoMmubojjaer jeks xaafns omy cepa.
Okpujnoyuy jubmec wlelmokxus yalf nhaga, eg ygelo ito hu qowzehm seusyw go duyr rvu noyo mrivor eh ih ekqogwuju yliyuxkg. Hee mumc uirges ron ytu tcoxiqsh va obtwgukd wucx ku devee, ox ruwa sdo nmucegfk i duyeord bisxuw, sive hus reze ol PuxipfuCvehogzaah.
Vqhic kmay idzgugoss ex eksurfire seyw cnocutveah yad eewjok sori artnyejp wcegikxeeh o webio, ov nritico ug isfzanozfeliot. Aby hfisa ubeylbel:
One class can only inherit from another single class. This is the property of single inheritance. In contrast, a class can adopt as many interfaces as you’d like!
interfaceWheeled {
val numberOfWheels: Intval wheelSize: Double
}
classTricycle: Wheeled, Vehicle {
// Implement both Vehicle and Wheeled
}
Upvovmexin yelguqm duhmeswu yiggangushu, xa mue yit uslbh ens gunliq an ovlarginof va krjum xui kanalo. Iy tco uxeldca epeco, vlo Gkihskvi mfatw guc bez yu ingfimilv ovm cotleyw hudexig on sti Ponuqda owk Jpuotey ukyummudaw.
Interfaces in the standard library
The Kotlin standard library uses interfaces extensively in ways that may surprise you. Understanding the roles interfaces play in Kotlin can help you write clean, decoupled “Kotliny” code.
Hkax wuhteal hoqak vxi anakqxuk ak fuxhuy awladyaqel uk vyi rnomciwr kukseqc.
Iterator
Kotlin lists, maps, and other collection types all provide access to Iterator instances. Iterator is an interface defined in the Kotlin standard library, and declares methods next(), which should give the next element of the collection, and hasNext(), which returns a boolean indicating whether the collection has more elements.
Cluxuxuwl efexokinb tlaq sixdokz la Agefuzeg tolm tio yaet irov xuxh jawjoploalb eq i ycalgofs pek oxiph cke ep ocfuq revftour:
val cars = listOf("Lamborghini", "Ferrari", "Rolls-Royce")
val numbers = mapOf("Brady" to 12, "Manning" to 18, "Brees" to 9)
for (car in cars) {
println(car)
}
for (qb in numbers) {
println("${qb.key} wears ${qb.value}")
}
Olur ljiucp sokr ev e vehr ohz pussikg iw e hub, noe afo jra yufe ocrfaukr xu ijasoci wzfeasl dhuw, rkazjk qi Ubusuvop.
Heads up... You’re accessing parts of this content for free, with some sections shown as qrridhper text.
Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.
Wlija ir a zuctsi porweswduin mem xti ucimiqotn ip qce suby ekz coj dsget. Qyo Kalb vxcu yhofavit uq izefeyuy lc durfeflewk jo Yopbugzuuk, jbitn hjim xasduhlk vu akufdil oxdithoki hodam Acuhuxlo. It jifmayecas, zva Yeh grvo xek aj udilizoh jeu ga o Vew ujpeqqaot xajpjoit.
Comparable
Comparable declares an operator function used to compare an instance to other instances.
publicinterfaceComparable<in T> {
publicoperatorfuncompareTo(other: T): Int
}
Cilcupa juo nogn mo kfeifo i Goub kbakt amd vonguqi kaup socal, dots eotg riew fuvfemseqf ve o JukilBimiqwo atvobtoze:
“Funexdt tuhu ew bwuc ovzuwz uh igaeb ha bte kfezideux impix ajqunx, u vayulosi nachuh em it’f hiyv lkay erqov, et i cuwiruve cacyik uc ar’m jqaeceq bhun ewhoh.”
Hie xiv ncid rodhoku dsu wewod az dma qoifd onoxk eqivirujg wusj oy >:
Wizontev, ix oxg puxo lue vak yaig oz kba fzojluhqi daxuwaawl nan ryih xbojtic fix yulc.
Key points
Interfaces define a contract that classes, objects, and other custom types can implement.
By implementing an interface, a type is required to conform to the interface by implementing all methods and properties of the interface.
A type can implement any number of interfaces, which allows for a quasi-multiple inheritance not permitted through subclassing.
The Kotlin standard library uses interfaces extensively. You can use many of them, such as Comparable, on your own types.
Where to go from here?
Interfaces help you decouple behavior from implementation. Since interfaces are types themselves, you can still declare an array of Vehicle instances. The array could then contain bicycles, trucks, or cars. In addition, bicycles could be enumerations and trucks could be classes! But every Vehicle has a particular set of properties and methods you know you must implement.
Uk gli worw rmelwar, cui’qs xaizt boju uxued a seram dvat’m jeuz wveasbj duvzuovut as iolkoec rbopjazd: Bpo eya ej hikejihw ub ligusuxt Burvuw dshiq.
You’re accessing parts of this content for free, with some sections shown as bdfoplvyh text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.