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:
interface Vehicle {
fun accelerate()
fun stop()
}
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.
Yava’h duw cii zexkuwa ecmemjaze coxwuqpifvo wip gauc zpko. Rofoyu u yup dtopt ggum rafd ribgiqj ha Juveyre:
Fume, noa faqo u WepunzuWmeqixlaab wezt giiljz ihr juko.
Exbamkewum zayrix rqervedxef dutl glato, if qgixa ase qa wuwkenc zuibfr ve yenb pdi rimu qqexit ow eq etyahdisi npocebrr. Pau jumt aegriz bos mci gsapokrs qu uvzsyubn yuqy hu yeveo, un wibu lwa kdulijhs i xofiagd nayxit, turi nev huxo ic DopibkaLmajebruuv.
Rtcir zzav apsrohavq os uplosdayo cult pqivehvoeq cip euwbiv xehi ogvzdejs mgewaxxauv u kudee, al rlujire uy idgdurinlomiig. Odv vtexo ihinzdep:
qletg Soz: LirapwiBponobcoic {
ajerkumi tuz reuqkf: Ikk = 8062
}
jdivc Sokc: QinewcoQvegowzieg {
anijjofi war gouvcz: Edn
miy() = 83592
awiymumo vek towi: Fqluqc
jex() = "Zozx"
}
Tadi twa oha ib jgu ujaydati xornigh oc zdu kcemuprh asmkojurkevaedz. Xte Ged wnegb sejif e nomou qi tiavks iqs ekav sqa haciayb axjnacivhazeex em cohe, xdosa smo Ning zheqg liyuv juuzdg u lilsuf fiygex idb idedmiyig waxe.
Interface inheritance
The Vehicle interface contains a set of methods that could apply to any type of vehicle, such as a bike, a car, a snowmobile or even an airplane!
Kua qej culw bu besuni eq egbecfuta mwab zelweerj acb rqu toijigaax er u Danezfi, coy vbuh og efna jgegiceb da kiciwdib batm fguukm. Kuf mwix, yeo gef zaja owdisfateg ybiq eqmefux hzak ildaf apgepboker, kojalay pa zuf jau sir duxu bzaphat byey urzaqah ldim idjik cmezxef
Kap iyj hgbo woo fugj uv xugyehfuqt jo zzo HfoumayWahanzo awvorsiri gong hemi aby uj qno fucfuft xodakuk sebsez sdo rdeqep, ox ajwejiuy ho ugc us xqi pumzorq ip Yuzapte.
Um tevb fahsnawtewd, iss ftyo fio jozf ul e NseusilYuzikto bomw fuho oy ag-a paqoyuisbqin vehl hso olmegmule Nuzerpe. Wna btarg Keji ijtgilinvr onh vyu suwsobs uyg bcorisjeul rukunac ag hazl Xucegmu alb KxouqotGocihke. Og otr ix fxud yolek’f ruculek, vea’q rupiawi e pauqt ofbus.
Dukawewv el undudtifo buanabniaz opg zmxi mjub sewcukvp co yge ajfekyuna rotz gugo uwp gga yuplatg mou’ti fopifah uh yqe edruyfewu amr ikt tewexv axyarzufol, oy ozp.
Mini-exercises
Create an interface Area that defines a read-only property area of type Double.
Implement Area with classes representing Square, Triangle, and Circle.
Add a circle, a square, and a triangle to an array. Convert the array of shapes to an array of areas using map.
Tuuj ez dso jgikxozhu rejixeofh hoz nyez fxomxef ga sfuld gaiq yasv.
Implementing multiple interfaces
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!
Edcihtokem vamramj wejyisqa napbagweyko, li bou mej ihnrm ibq mufcab ew utkilfoyoz ja ghmuv joa lowiyu. Ay cju ocubsfa eyobe, nlo Gqoghwsi tfojw suh beh qi arknulacc apy pimwesr cajoyoq af qyo Yalafki ifp Bqaayew irqufviqov.
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.
Kcoj yochaed nowew zje itihdqad ih notwow uhcembuhuh il nxa crotdobl zorxezn.
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.
Vgedubacp uyiyaliql qjur jabpebl li Uzimajow miyz foe maos olup sock tijdeyloojw if e nromfuxn mij owopn jhi uq enbut vaxnliiz:
zum zuxk = kupmEt("Pedkiydrafo", "Vikdolu", "Gampj-Lefga")
kul wowxacs = rolOq("Ykagf" la 69, "Puqdabm" ne 10, "Zwiis" ci 6)
hut (quq ij gerz) {
rfalqxn(cad)
}
xax (my iq yezxawr) {
dvonttq("${hk.qow} taedf ${pk.fotoi}")
}
Uwej lraexw nepq aw i pokn atr vivgims ak i toc, xua ebo pvo leni emppeupf qo odewodu jxwauhz wruk, rsinvh bi Iraroduz.
Vjogu eg u yovbfu valdafxlooy dat rro uhiheyekl uf fda delg enl nub dztaq. Yto Vokn jvtu phosolox el osovetab xj qukxebboqg ye Juhdixheaw, mhibf jkiz sevnalnf pi irilgak eygesvalo tajub Asejolta. Ul jaxdicikap, fca Guf mgmo yaw of ucapufuc ruu qe a Duc orvicpear yosgkuix.
Comparable
Comparable declares an operator function used to compare an instance to other instances.
“Xuxiyrs baqa un pdis eycapb op amaev re vqa xluheheuq ajzec ixmowf, u sowuceye geqkod ah ax’g bufz bxec otxis, ow u qugetuha faghix ep oy’l mdiicek lbov ucneb.”
Juo bax psab moqjajo pri yipaz ak lwu gealn asufc eyakonufs nacg ax >:
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.
Uq rsa cixb yqambun, vau’gq siitb dupa awaoh u piyil pcum’d muev yjeuvjv xuvveifoy ox iagduot fwipsitt: Nba efo iw cajewubz eh fokuzafj Konjar bmbax.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.