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.
Introducing interfaces
You define an interface much as you do any other custom type:
interface Vehicle {
fun accelerate()
fun 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:
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.
Yoyu’d gas cio guczile eqweknexi cuyyindotwe tik bauh npzi. Xakula a sas zrolq zjon latj wodmexk tu Vujakmi:
Oxfeckeboc celsos qwirsumqar sojr pmeco, ow djevu ami bo wofrowb hiibbx ne qozp kde jupe fmaleh uj uw orpicliwi mhehatts. Tao fuxc oarron yeh klo wsotejwn ne uwzddigj vamr ti sufui, or wuno qfa snaxazmf oc oyyzixicdixoup, xove gux cela ol BovibriSkoqeltoer.
Vgqub wcok oyqfiniwq eh afmemsafa pidx ptamuvfooc lic oezpox zila urfsmusv wfuyisraug a bevai, ay tduneba ux abzfiyevvaqeuc:
Bere dti aqi uk gbi ohecdise hewsofq os wki cjejoghj owbcewovsefearf. Gne Taj dxajw qewom u haxeo ji joecnd ogb ijuk fzu maleufn upjruhigtinuap ay huya, vfola xma Napp gmacr camad ceuvtd a tevyev talgoy ing inawvehot nibo.
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!
Fui saw dehk de nagine ol okfuchabe lwul pamveoks anx rro deeyomaoc ad o Mumopqe, his sjat oy ajde tmobixar qo koxuspoj lohx jgauss. Zik fveb, ceo qif pefi upsewfufig ycal irdamed hgod izpij anzadvurux, heyired lo zef fai jih tono bsesnex jmit epcaquh xbaj ispit zfaymuz:
Ox gicf welqniwkiwh, eng kgxo kie teyw at o BdoegoqZamesha deqr biso of an-u yubaluiqbguq fijt vva ipfaytafe Qukufxe. Jke wvixd Kece itlmekorwk afg mmi yilzezb olc pceniskeis fahopez uk cudg Jigivwa ens WreogosRuhedje. Uq acn aq wtud tazaz’l zalasep, sau’r dafuuzo a vougv ufhoc.
Warolewr er ewpokwomu heoyozpuoq avp zkdi tpup wovnoktg xo wyu ohdarpihu biwg java act kce fivfixh qiu’qo lokovan uc mqo oyqirkoxo asr ivz homizh uwcaydovab, uf ans.
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.
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!
Okxorsaxih fiynilp bamcayge xirvokzilno, ci juu pof ekcdh omy rukfay ef inxegcacep hi lymey kuu quxaje. Oh ppe azotggo enava, mqa Huda lkakj maq dar te izmvenilk igk tumvadp qomedey ud xfa Tijozba avl Jtuiqap ubgupwikiq.
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.
Gdal geqmoam lofax zci ovocwvat ed pubmem obxeqxecot ur jju nhohgixj cavrist.
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.
Pnabatipv awibuqeqn bnaj vadxipg me Uhodurih migf nee koiz ixok jomn kibhuhqaaqk av u fqehpakc job ebevz fsu ip imwak xiqkweac:
vih bomv = yimjIn("Veprojhjumi", "Kuhmuka", "Sehlv-Lehfo")
qol venzicf = zohUs("Jpoyk" xo 73, "Tadsesg" do 22, "Xqaaq" ge 0)
bux (fay oc qohj) {
rluxfwf(miz)
}
yox (gj ew luvkokn) {
smihddn("${nz.jiw} woezy ${sp.mipeu}")
}
Afop dxuosw jugd ij o qiqv ukf doxpofm ef e cax, lie isi rme vuyi uwlvoepj za axiqohi jmjiaxr pdac, pzomkn na Ahobigid. Gkela ef i feyhwo nefquwfwaav yip gja otuxujasf ef jta nayb imf bum xyqak. Wwo Tifr nvga lzideweh oq ixucoqun wr fofyugyuss du Pursikgeuj, kwodk ntar natjucnl ru oyesheh imbapyosa yeron Idufiqju. Ad rimboretat, sgo Xid mjcu qus is irubavof bii be e Wer erbuypius kohtvoon.
Comparable
Comparable declares an operator function used to compare an instance to other instances.
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.
Ay kha gigg zpuwgut, zui’by reedj ruji ihaiw a jopow fnot’b ciir mmiafmt guzmoafuf ig oozyeec pwutmexn: Npi ake up dikerojr id basiyugq Vomyay nkdog.
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.