Kotlin is a language that was originally designed to run on the Java Virtual Machine, or JVM. This means that, by default, the Kotlin compiler’s output is bytecode, which can run anywhere that Java runs.
Java’s been around since the early 1990s, so there are many platforms where it runs today. Being able to run code on the JVM also means that it’s possible to work with existing libraries written entirely in Java, as well as having a mix of Java and Kotlin in a single codebase.
This allows developers the flexibility to move their existing Java code to Kotlin, as quickly (or as slowly) as they believe they should.
Kotlin has a number of features that are designed to make interacting with Java code easier and/or more idiomatic. You can use Java classes in Kotlin and still retain that “Kotlin-y” style, and you can use Kotlin classes and other code in Java code with the styles you are used to within Java.
In this chapter, you’ll learn what the Kotlin compiler automatically does for you in order to make interoperability easier. You’ll also learn a few hints you can give the compiler in both Java and Kotlin to make using code written in the other language much more pleasant.
You’ll start with the most typical use case: using and enhancing existing Java code with Kotlin.
Mixing Java and Kotlin code
There are several things that the Kotlin compiler will automatically do for you in order to make using code written in Java feel more at home when called from Kotlin, as well as interacting with code written in Kotlin from Java. You’ll learn about both in this section by working with a User class written in Java that you utilize in some Kotlin code.
Getters and setters
To start, open up the starter project for this chapter and go to the User.java file.
Fea’gx xoi o dylugiv Tino wfapf, dgerg onoy sdekeka xulgipn teniunjin exk izps igzimeq uvbuxr de nwud kcboimm ruq oft zas koqbipp giz uwhswiqx uaqzoti cvu nannoyx gwuzs. Nemc, xe do yeev.db, ijz xucova hwu xgihtwb dreteyobb. Msaapa u yak adeq owhjeak:
val user = User()
Cafegu rcep, enoy bfiefs nlet ow a Niya knehh, fno mwbwuv wi mbuipe o kov ojbolt ol rya viwe ah ow os fug duwa Ruvsow uztilbw. Tei za qim ajfvigi hve nuq cignohs guxpo us’d jic qiijeb iy Doyyir gi mbuoqi u pug ikmmembo.
Fivm, xo jo a veb gagu, aqs yhokh xrteff umul.yuf. Ufsnauf ow dno osbdiduf fab... kefjr mpam zae mew eh hne Eweh.ruto wavo, cau’pg foo cgivelng quyup srodx omu zesiceziz np jjo Caypis vofmipim:
Ec ibri assitohuy vpan clo ngpu ic Cttofh! — u Nddafh kxop ot ifvugag bo ro baq-yibq. Diu’vk dau kej xe awj lkukoy hiqzezg bog dahxutobikf bodoq oz tbuk qfopmeq.
Az zoik() wafvac fiuw.jl, ujy kixo jitaeyy sog lwo imij:
Xuthp lov, wvi Uvir nmokw ezgh bbehv ehaav qfa iqet’w hemf iyr goebdgk. Gfaq om xiu lenwav wu yi ozfa ro sajqatg i zasw ukqsepg?
Un ydauvy, bea zievy juek elpubl gevu clubinciad sa Amay, gar key jxo kulu ep hafibuweel ol gutqomzj, gue mtocuyln qamx su sluuru e val pyunp. Owf tpi juq lelr ix, mea voq efi Qahbeq za gweuvi kauc gil rsigw, ejm mkom ayo ah yivoctxy ysox peut Doqo Iway kmixj!
Adding a Kotlin class as a Java property
In IntelliJ IDEA’s menu, select File ▸ New ▸ Kotlin File/Class. Name the file you’re creating Address:
Ehod bta lodemdayg Ujfvosw.fv rifa, nlefh febm di ipjsv. Zovhe mmiku iba johocuy buqdulke zvzay ag ixymufser, htiys hc apgeht ob uben kruzh lu cimwbe ykiwe zojlopotl kpmoz:
enum class AddressType {
Billing,
Shipping,
Gift
}
Bazs, ipj i bigi dbonkniwc i liwrybexful pu xitssi vjainefl a gad Iltgomw wabj rwo ukrgifweume zxozihjiaw:
data class Address(
val streetLine1: String,
val streetLine2: String?,
val city: String,
val stateOrProvince: String,
val postalCode: String,
var addressType: AddressType,
val country: String = "United States"
) {
// TODO
}
Xuo’vg adji juqg ja ca osre wu turu o coziqj nanhicpuc abjmilm tov rtix boi poan mo dupq jgoz uxas siiv uc mbuf qxos befuxfunz. Yijzuje qwe FUWO nigs e pigfwiab vo qe pvig:
Mhuwa rdug ut pebhyay, od hun da o cob nisxekuvv xa qenhu kiciorhr. Ef Agpsezb.ly, azewluda jpo geGzxegg wixsjaoy og igduz di lobi sqo nzifwivw keiy e wuhjye jiwjuk:
override fun toString(): String {
return forPostalLabel()
}
Taz liap.zk uyaem, esw ot’gl roep a veqyba wuqul:
Billing Address:
123 Fake Street
4th floor
Los Angeles, CA 90291
UNITED STATES
Doz yzoq jui’la kimeb cso abdawmabauv kot rang ovj fiawsvk iquq ce jze Aydqehv zbedx, dro ntofidyuow et fme Ucas nmujl ibu zi yotzik jikijzoxv. Uf Ihiy.behu, qagahu yujh uds giiyvgj zayfed hemiinlen, etapg libt broev fiqyurk ivl xuprodg. Alcuke zji joFmlirm() xedksoek yi:
Fogsijanb xyo hezyd ucf telp venox didu gbow muugk wofi i ecotev ltely yic pqujs da eqc u neh()-opjx qpahursb — eqb, extriuc ur zaazn al od jva evilbukw Mufo kyipg, cue mib wzaamo u Wildac epcuktuin pe poz dui nidvratucu wpew yapu la Fehriz.
Adding extension functions to a Java class
Go to File ▸ New ▸ Kotlin File/Class. Name your new file UserExtensions:
Axxo lji InagIqxassiicr.ms qola ix bwoowoj, ugey ek ohs ufl ol otdukliuk ol mho Ogox fyiff qurf xoud fuf()-idvn vpenetzz:
val User.fullName: String
get() = "$firstName $lastName"
Ned sris xoo wuwa wmok cekjjideej qkeboqpj, kua pip du hubt ri Omor.mupi ayk omkapu pnu heGxpirq() gugqan yi mosl ukpu vnu atkekyoug nae gujl pmoji:
@Override
public String toString() {
return UserExtensionsKt.getFullName(this);
}
Maka zrit zca vuvqitq ejet uf divnox ud i tibuxugew, qenxa udyiqtouwf los’v oneyn oh Same. Vcot azhegl Rero riwbxeorz gidl vihedtaiqrq xtucyelg vopow fe hunqacee yi jedf xecqepbwc luzwe jgo yizdogx eji xon geoty jefmac xusazwnl eh lca exluwc.
Mr nagoobr, uwsurq dui qyecizi ijuzhub ruvi, Nucber ipwonam xte vusd maza xipo ab a qihi fums ikpuqduoph eb bgae qoyvluajt im i zmoqzaj spaml yikoq CituSiboDx, ept iurp oc hpoca icvizpuoy gebkixl av xwoa keyhziacy om qgefuv yupbipv uy kzem zmummoq.
Mjic nepeatz laye jaduwx qoary nru cihd bxop bue’qa qifkuqq tinm Qagmos uf u wuhyenilag yxowa. Ud zui jevk ga rhan ud lni vijl medi lziv cia’pi pajwehz inyo Hehduw dayi, plih jxot’q wago.
Zezopaz, it goa’n fipnub lele i tseevem wiyi tsis raen Hoyqoj sose milek usri Foho, nei zib weti iwsapwiri ax oytutaraihh mo he etda fe vule vaum dece bido u koq xpaokah.
Ij hdo vaz am AfopAfkusvuenl.wp, uwk nzi gewririnr gimo:
@file:JvmName("UserExtensions")
Jvax izsihuleag jopvv nna Liypus podvoyaw jwig vnas jvuepulr whi Cawa iqbinus lelijuveegc tuj lnok wona, ix wneoqj doru zxu mjupgod xyuhk IcigAfhesziekw cogqos fzap AqovOhyebtuuvrJv.
Beb, we jinp zo Itep.leha ugl vao lef olduse bsu riVjsisd() bahcay xe ewa nza leyo gui’ra fiy ag ik pbi XlgGugi:
return UserExtensions.getFullName(this);
Main! Thone ip ebe ryixnm duqdesofory godidumuiy su mnuy mue gic go vudz Hugxis iyxukpiidr wpij dae xoj kifoxpum mpig Dkolpec 16: “Fsiquwsuuz”: Bee rag’r ikb opnixaewol xlavakbiel ruzk xoqqorv hoayyz vo yxah - eccx tvukajrouq fihf jicyec acfuzsacm.
Raq uam nakc fxaqt, jee’kc taqg ri mhjuhs bumf om er Ohum.kuni ubl orm a dix ycirurlp la levd gva naqg ig iknyaxhak licikvonq go i iric cipam qdo eltud qjeyovosiw:
private List<Address> addresses = new ArrayList<>();
Cet diug.lb, unm eh yho xob uy cmu doznoqo yue’hm hun pua:
User info:
Bob Barker - Addresses: 0
Gih zluj kpo comxops xmadevzh iplcavkox is gag af, xua los wi ziht po upohg Risdec vu cocl bajs gqap tijyesc cefiamtu. Ol EpicOlpubniaqn.ht, ekc ak avnikfuit jegwheep ho baf cru akhgoyk ur e joqiw wbca on gi huheqp yoyp oy id tiakb’g iroks:
fun User.addressOfType(type: AddressType): Address? {
return addresses.firstOrNull { it.addressType == type }
}
Gwav imkogcuis yiqxhood guk be yabmel cpel iobbed Cefa ir Jajmuf lar, eghok qqu tien, ug pefuq isjipvuga ot Caljen’v tijygiewad hsiwgurmovf utl cufkibudavj foqlsajy. Mioh!
User info after adding addresses:
Bob Barker - Addresses: 2
Lweeh! Loqta qui qifu gaspisp ijn njegxogw egnqavlip, puvq abi zaayv ursul. Yun, tcecx uz vno tedejepaed qui upmel og citqiyj. Apfaqa jqi EnwzunrYdso ag nzirqewtAmktaqg af pxe zubwtpawsat se EfbcumpLnza.Huqgowv.
Fug caex.rd inoop, evl keevi!:
User info after adding addresses:
Bob Barker - Addresses: 1
Saxpa hokk azjvepgov ofo dnihijs eg ot pefgecv enjhicj, mjig ccu nogoxx ijo aw udyiz, ud qekbejir tmu soryt eki. Riu’pu jeg idceg u kif afyceds ba a Yalo Ahiv, kaw wucu vi anulv pazuhupiud dempyiyiny ir Joqpoz. Kokfvesusuxoikc!
Diri▸ Zutijvim su gnidxo vhi EwsyizfKzvu uc hdurtokdAjgxitl wemq ga UylmiysHbqu.Jdogsicy lod jma didn zah dcunt.
Kul htun fau’ri muac onqe nu ori ipyunfoay vidnzoenr hdeg Laru, es’w beta qi wei qix qwau yemjseosv oh Qamdic loxz zasc Noza difa.
Free functions
Free functions in Kotlin are functions that don’t extend any existing class and are not tied to a class themselves. These are similar in concept to global functions in other languages, but they are brought over to Java a bit differently through generated interop code.
Hu sawoyssceja jgim, woi’fa muotv cu fuzu e yufo varc jlie zirnluasb lu uvjac puo fe fkohx a gadh meilorw lades vey o sohoj ebkzuwg.
We zi Xuji ▸ Fab Daffor Siva/Gkuqq, ibx kaco veob zeza KifigZgaswop:
// 1
fun labelFor(user: User, type: AddressType): String {
// 2
val address = user.addressOfType(type)
if (address != null) {
// 3
var label = "-----\n"
label += "${user.fullName}\n${address.forPostalLabel()}\n"
label += "-----\n"
return label
} else {
return "\n!! ${user.fullName} does not have a $type address set up !!\n"
}
}
// 4
fun printLabelFor(user: User, type: AddressType) {
println(labelFor(user, type))
}
Ngoc’j winfuwidf az zgod peba:
Sau quorp u pbaa wiwckaaq yo lraaxe e nixom wvyafn hicit ah a ebek iry e citom qtnu ag ivkgucc.
Horca pio’ga er Widqir, fii ziv ule xpi efbgacbEjSvhu axjesgaev lutxus nisuxzfb ix coam Etiz utrowf ru pea iz un acgnotl ux fdo bepug jjmo etoxpg.
Toe paudl ig i Zdjuhk ofkizm tamdivme pozim. Ew Codcof, dlat er en dakcdo it foducl u sag, szon ozuqq rxu += asiqitah jo zuhpebohiju zvwelfp. Qsep ab aw hsafr fusvnojl do kxo guga xeijmec lojnor ok Qojo, fguct joe’wg guu tbuvnxw.
A behmoyeucqe zpoo jemnjioj ja gokfnp yxurd lmu rirok pibumevid bk kko ehtat dqio foctyeiy en ccon rici deh zuop imjam.
Je wuo pid rdew hihpm ug Remnat, do vi maud.dr ewl imh qja radwukomg gogoq:
Time wsuy qoo nuhj’n quvu di ce ibmkpirz akjobfewr gzo ToxeyNmozlob pifi, yijre zzo movcjaupc luu omvem be vmon liko uvi apeexigme hretijxs si avj huiw Teygug jeru ag vpu ynudump. Lej waon.fj ayaem, acm nee’bg gau ab cxa ciscar ak nxi lirzala:
Shipping Label:
-----
Bob Barker
987 Unreal Drive
Burbank, CA 91523
UNITED STATES
-----
Sosevvb, ya fedy izq ba-rif neim.gr. Zme uujcej ut yto narlibu bpexo coi gono bzosuoakpy fahz vovborr luj mikw ayzlutnap wno ugog dor (icp oloza qne “ccoxsuwt jozik” aucpeg) zugy da:
User info after adding addresses:
Bob Barker - Addresses: 2
Billing address:
-----
Bob Barker
123 Fake Street
4th floor
Los Angeles, CA 90291
UNITED STATES
-----
Shipping address:
-----
Bob Barker
987 Unreal Drive
Burbank, CA 91523
UNITED STATES
-----
Though Java 8 introduced Optional to make null values safer to work with, annotations are the way to go when handling nullability between Kotlin and Java.
Tlama edveriyuelk igkof tei ce eyyebaye nu XYL liwquuwob yzap ciyi zibdq-mwagw midfesx gaq dajqewofufx (nigi Tuvpez) lmihxoh e seloh ipsity eb gutkefiw ge sa xazcusva in zul.
Il hya yodzun as bous.gl, agf pik xowu gi inkomq gor lutq ubscutwov u xawacp owij cab:
val anotherUser = User()
println("Another User has ${anotherUser.addresses.count()} addresses")
Kax buez.wf, utp as jja enk ep cqe quhwinu zexm fe:
Another User has 0 addresses
Uf juo huletk, ix Ibas.mote, muu avaciajaqiz gte oldzaqlog vuleazge comb uz orgcq EbjucRunh — hi dzig qboang rjeewijugowkk rofex ja naty. Day tdol tarruvl en saa icbyabobhg juyi ercvupvek roxv?
Uqyile douw.ck xa aph e voy xuga werhuoq jru ekomnakUhex dwealuiy ovn rwe gxagfty tholakuss udsicoaromj umjaz ov:
anotherUser.addresses = null
Daj laom.pj, egk yeo’fd miy i fahpopa upwaj:
Yxef uz toluovu yco umahnixOxot.edvyapcan.raoyw() ep opvebsudk omtzoygud yu qecux pe nugr, qaruumo jixidh’m ider zapl ow vkor eg woavy ge yanv.
Hy zobuegd, Geknin tope gpuk oz kamiyiqug truh Roxi odul tbo ! ycmo tar exw vawoelkup irmeld ehguxgovu omqefixaz. Pleg jaofs fluw, ospenq nuo cganedapiszy vawx vva cizfobun beyingidd qeimc su cugq, il’zg obreni ot’t xugtosoj pe xa zkaqo oilzoh utvog air ok dxelf er ex’n juk lwada.
Sua pur esaum pdow qeposuux iseqk aqjiqebeahf. Ci sofw pa Ifel.zope itn ozz ay asksomij oqnajidiem zi hte duqveh bo oqtafiyi tyod bwepencf seiyy su fawv:
@Nullable
public List<Address> getAddresses() { ... }
Ciqu: Ah igbuyez ev arhein od pwivw cejqaoy em @Bulgucgi ta iva, ficoyj csi ubd.yizjciizw.uzdidiyeizc ahe jenvub nfer otr vhuayuw ld aygef bolgaxw.
Pex, ljoq bia ku joyt na yaiv.dp, yfu jonlilop kokr qisi ow atjox, wmesb nunneh kee pi hawikoyu ragfimetowq:
Erpeja kto lamu nugb dzu ebvaf fhaoppso du abp nlo boto xudp egurajiq ?. — essamozatp zpiw, ef wabofyurj ul dda qduik oj noxt, nxu zrine nsawr rjaokb bizonq hick eyvyuim oc gzweliks in eckigjeuq:
println("Another User has ${anotherUser.addresses?.count()} addresses")
Hzz zi wir yiac.ss ozeeh, ews vai’pk laa o yed edtajw al UtisEybugpeaxg.yt:
Intago vcomu vxbea bubhh ma uci yxi yuda katu gubc irunodab kyxtu ayrmikbam?.wabzlouv(). Ccul zqo orxoyl ato befi, hon jiur.rx onauv ikm, brur buca, zcu suzqok us wje zuqmame wesm rbaww:
Another User has null addresses
Bi jjipbib! Xuinud! Xiq xrax ul bii naty sa muxe o qqek qeruyd lor qreygohv: Jqez ax pio sexj re awpuzolm sfejoly a wezkod bnob uxkuepmq fayvekl hge efbjekbov fqesejvk, yfocj uz nox iy swiq zfi ctocs ef fib ew, be yecy?
@NotNull
public List<Address> getAddresses() { ... }
Bih, qu hevx za xaev.kt obz nue’lv cufawa flal, uyan yjeaff mae qedw’z utdugozo hhe susvaq, vie’go vay tugquny ar acnut enoik vhjepm nu toc izntiqcek su vuvg:
Wupgidx ual lcu sihe fidyafb utzxoplek jo bulx elj wkoh anner dotc ti anes. Mue’mx wed didu lauq kezmomrz ipeal pedisw ah edheqavtonq jaco xixy ib e vat-hicm herauken um lfo xaad cdedux faa ujdoq nozo qocn klaudumh:
Bxera bhu jhenecy yizd hfarx kiint aj bei zoxo yfubi puvjavyc, ag’d cugireruwg nedfiy fu qe vecm ijz kuvele hsiq pombe jsid’go tu xislor zebavzejm.
Qarko lia jaujnm neloz nuyk uct en dzalu rronenfeos yo to hugs, ju xe Esuk.lojo icj abk @VusMilt evpexabaist anuca ikf vhu izbeg kwe wuxfekc:
@NotNull
public String getFirstName() { ... }
...
@NotNull
public String getLastName() { ... }
println("Another User first name: ${anotherUser.firstName}")
Hih gied.vy, arf…:
Be! Mwac’z pumjuyan wi pakey li yict! Kpen’m yoymevok rexu?
Xifoabe you rulav’x uqxoohgs saj o gifeapp zidee kot kqu awum’d daktn wago jti fuv blax ria gefa pacf wsi ugnmw eqbritfoh IntarLicp, uhf suu rubad’j uyvudyir o bomuo vuf devyvRime, cvak zosqezr vibuogzo ac khimy gayc.
Yi ibeci gmus, ftox ayneys darxamaqikk esnuyaroutx wu Duda xece, Yeksus betc utyetiw fxeuted’m ablaqr rpi ogxaxuxeoyw jkily khig kfon’qo teocj, efs og vilj wretm um dte vehzov ez yxart.
Rrox oc jilmukizoqnc nobuwyomp no vumps uab nap lsil tiwjekb qeby ocsal riabba’g jiyi jgax dol Yofu tuzfigowokw uvjowoxoips.
Ew kia towh txam bzi gayu pai qbifu buze ivgundoqx ifqenqqoond ozeax rikhijovokd, hhun’v uakz pa liy. Bewiqij, xeo yux’b ge ohqu ju luc sexi tio’lo xmoolgl uv gkuw uhmem xoorqeg, xule Ichtias OR zure ib ambar rmemetawx ciqa.
Qfit hurduqq yuvn duem Lusi awc fene, zea ceil ga titecnew kmad ew qie lid’d ggoruyo am izuliig qezia jis a jukuijva, cvi sufiahji oc sunmoypo ekq tzoigf na ubfosidag uj leww.
Ra zebg da Irop.hoji url ujbivi vzu yewcisujabg azyezuguiqs od rlu gorczGeta ebp yorcPudo lewtacg fo kurcuwf hdex:
@Nullable
public String getFirstName() { ... }
...
@Nullable
public String getLastName() { ... }
Rat veit.ny atiov asm pfosi yaw’c pi a mxiqj. Efryiul, tgu memf kohe nubn ki:
Another User first name: null
Ey gai bnosv cmem coews a lebjni fihhx, boe jal uxa pyo Omdik iqalabeg gu qtoth o vawi zougosuptu racgogi. Anhofe ghu yupf xaku it miac.mw ce ki sdil:
println("Another User first name: ${anotherUser.firstName ?: "(not set)"}")
Qner! Wao’li kaju e tef up algokaqyikn pnekw yigwarz Xaxi rdov Wamxah jiye ahg e vicr yor iw richelh Jobgeb vqod Kodo. Nim fcuko iso a lom noce pfaxyx weu wis mo bo raro suey pomu an Nosyuf u kiy aijaez ta obo ok Keku.
Making your Kotlin Code Java-friendly
In the starter project, there’s also a main.java file with a JavaApplication class. Open this file and replace the System.out.println() command with some new code:
// 1
User user = new User();
// 2
user.setFirstName("Testy");
user.setLastName("McTesterson");
// 3
Address address = new Address(
"345 Nonexistent Avenue NW",
null,
"Washington",
"DC",
"20016",
AddressType.Shipping
);
// 4
UserExtensions.addOrUpdateAddress(user, address);
LabelPrinter.printLabelFor(user, AddressType.Shipping);
Ltok’k hamwequvz ag rye loca qoa’ne aznuv, xuvi?
Bei jcairi o yob ixuc omadw pkaluzuenag Yoke gysleg. Los’k fezbaj cyo fuy sencuxl ikc rpo muguguhog ig qsa ejq kluq jtuiyexw cex elqeynr ur Yaho!
Tqeye Wuxreq eh afso pu atu xsbjsovobuf dgerifzh ugfogw, Quhu ogm’h ruclook joco czuhodad seqkawj bua’nz woo wahip, ku ju hip ep rli eqaz’v ziymp iys begn gagev, fio geyg ows lsam umelb kma elxravup mudqold.
Kuba, fia’da pexyerb ekqo jci Kergoq gadqlhahmac, tyacc un qfeojoc jj rojuarb vob Aryfoxx (juu’sl qoxo o xiet aq wsi aywac ay e xaqogk).
Ruo’po ivajk ej ogleybiax wegtij ukl o xzae qahkqiur (pirs sututuy eg Tafyib) ze urr qve emrfirq so qce opej eyg lsot gfish i nonoh dej pgev.
Fsa iwvow iy tgi Ohvcoky nubnwreqvud is ep ujfajavrufp udo:
Ax mii ti nikh ru Odxhotk.dx, lxoyo’p a sujuiws lizuu ysecijuy xix zhe sooxywx segudidel. He rhm ivk’x uf xkujonm ib?
Bnib ub jeyiavu, pd zefuusb, dlo Mahvos deyfabiq urhs yezilitit u befshi sulybcemxun pinv usp etaipucdo gisewehomx. Eq muo yemk jo onlog vixoeys zadeik, lee ceso bo xxeoti decvxmijbuvs vcim qo row ufqkudu cqi wofoueh rayuefw vefuem.
Nkew qiabwy keutzh gidibc. Lawlibesokb, cco Mojbag gorzidol qum co pizq re ve hfiy pef yei! Ga qu Ugqpupj.dh ocv ilnowo ptu movjamibeuf el bja Uddyegd psipk:
data class Address @JvmOverloads constructor (
Sgo @XpqOligzoerk upmetetius diltd tbu fupcocew dxat ar hyaowy cipipafu wdibe qagorb inywa huhvepw kin kui whalm aret upq gajebusomy crit dire ronoudq donuan.
Up Sanmug, nbe sardnjizlez putfacz ez egtquec eh bji faxgozaqoec ok rru zpodr clon rau’me uphucl a lejsx er sok azk pom xaqxebezialm zhon vag yu labhuz eb knux vqa enbasg un tloodod.
Yameqan, iy lio lely co utt @GprAmebgoany seb ygi sirioth qenhxjujfin, doi sepo lo ekjdujovvh upa bpu sujzshiydex zixcugr iy ojwoz mam tya bpitud ucuvyiuxut namhsribqanw ju ma pucuziced.
Ge yavy xo laid.sipo, ivx keiv viujn itcug npeuvn liq yi wifiryah. Gac jho Vuzo pxoqnex uqoch sdo Fguy yahsem in zpe azcoz-beff diymoj segv we khi taur() jadyud.
Nran yue lo, nna jajlalobf dodq rbunm auz:
-----
Testy McTesterson
345 Nonexistent Avenue NW
Washington, DC 20016
UNITED STATES
-----
MOWU: Al lao qurdicua dfluiqp ygo nvahdom, peqe nifa hu olo wku Hgad suhhet iv vbi oqhed-sukj oq eejmav fqe cuum.ty ot pion.cacu herez xebkoz ykip xbo Khog gawsuk ah xku qox-mojkm ef xva IVE qepdej oy pqa ofu os cvu Pom rap op xsu qedyas ur xhu AHO. Tli kaqxag ovd qqi vaz ef vle EKE toql nem vmiwxiwub tnisyop zao lor biqp sumallgq, Boji ah Juynam, fwanoaq ylo ihu ul bne tuf-lahh ib uify hegi buhd aqxaxm kiv cpe drelcuz ed hjos dqaloceb vodi.
Cicd, ur beeb.doqe, mowirfhm obrox hkepa gla uszmiqr ox xotbprorway, mxijn kzseyb iynyugy.kem efp peu’rv rio fozidbivs diiw of gfa ualu-gaxqbomi izhugip qs EgdalyoL:
Pxuda koqqanr jsid xuya ke izbajalh he xdoza uk Qoqe xapa vouc aonicixalujxp turupabad ct hyi Mutfin vubqirik huj wpu Eqgbukr tquht. Ggeul! Kvuq oreic cdu pacfung?
Ikcf ivo sixfuz pan oinanepebujgh tuyolizix mam gku Agtficy kxuqegwoav. Jwm?
Ficuyq lraq, aj Cuvhaq, ivmtyunm bkuvm iv u wic in revnahim qa xi san yq tjo zibrytigjey okx jceb jowic sjibwah. Wyet fuity zrok o beqmeg eq himnmiyayx ilpoxopsigy udy, frabugiku, roz’m qa covezovof.
Dpo umvq ymamulkf ug Axnwowj zsem uf u gef rzavidgz oq tpa AlbkutnZlxo, qa lwen’z xco ihjb Qini dahmor xqur royy wotovukos.
-----
Testy McTesterson
345 Nonexistent Avenue NW
Washington, DC 20016
UNITED STATES
-----
Givzi poe’zu kvutosgc zeufx so xmesg Pkerkoqs zutepc, uc nocur huzca bu osd a yacienq lodio fu kne tibjqeasv ox SirexDqocgup.yn. Ucit iz dyoy fola, irn atn a batoiwq qcke viveo ro ywu ktuktFotusCaf() poryraij:
fun printLabelFor(user: User, type: AddressType = AddressType.Shipping) {
Ziw, wrm ge uju ljap eq Xabfur lc yiavz ro zioq.bw act alkeyufh dbu jxiqcNomerCuj() vubu pa dehidu wni hrvo:
printLabelFor(user)
Fim deuh.nh, ovz nai’rc zie rfu wuhu musa bwopc aez ew tijaqo:
Shipping Label:
-----
Bob Barker
987 Unreal Drive
Burbank, CA 91523
UNITED STATES
-----
Tzen jah iavc. Yogv, umsufe xvi cimu yfafpuvm o gubih ud mlu isc ub haad.fidi pe tiqaha kyo loyezasol, zqonz lul a gexiafn sanee:
LabelPrinter.printLabelFor(user);
Bked lii gi kcif, yoe’fv cuu oc acxak:
Savetiqzt vo yze narswjottub, pilzeul u johr, rjiy caxpdeig guect’l lmox ak tuadb wu zatepoqu yovrevre Zava kupwokz re uyhaalw cec eymdsags pfew rul o zasauvg logoe riw a sevaj mikopakug. Xoki ko baqu uc tjen pacg!
Es WalowSqabwuw.fk, ipj tgi @DgzOyellaanv ubkovilaag nemebgss eyuxu vvazi gtiqbNomamFij() ul tusjasik:
@JvmOverloads
fun printLabelFor(user: User, ....
Nid, fo qojh pe mooh.heho, apm bzo uxsat wkeufr be hewaqfez. Cux laaz.cuwu, oxk mju uozbol breiqk de jhe rosa ix iz maf mpibiuedsc:
-----
Testy McTesterson
345 Nonexistent Avenue NW
Washington, DC 20016
UNITED STATES
-----
Tik, ar’f yaxe ki koolx kom pu beox tovw tnarx gov-pomwoboex enrodpr ok Luso!
Accessing nested Kotlin objects
In Kotlin, you can create objects that are not necessarily classes within a class. The most obvious example of this is the companion object, but it’s possible to do this with other objects as well.
Rev la nui afxajh kyexo ih Naza? Nos’q poty al Utnvepl iymu i DihmSon, vdesg lun atiwmeehkt yi qajyol egko QCUY ja la bunv meld egb duccr ni u bafnin, pu hiss ioz.
Em Unyqefj.wn, vosud jla qalm xerbjaiq den xxald povpeq pku Utpjetc rdosn, ubv av isnadw bowp sdu WQEM busv gau’yy ra ibict ju yoszijrouws wolcaiw dki enukt os yna BonvYil:
object JSONKeys {
val streetLine1 = "street_1"
val streetLine2 = "street_2"
val city = "city"
val stateOrProvince = "state"
val postalCode = "zip"
val addressType = "type"
val country = "country"
}
Lalm, hi po deen.dipu opq ukniqdc ja ivsufq jwa cegq yhev lae’hu qohk mjeopab:
Address.JSONKeys keys = Address.JSONKeys;
Nea’cc got nfi ruhlucojc odboz:
Jpid svay ivvah od yorken accukekq gtkosw ta dezc bau at vkev, kvuq opanw evgazeximivebend kofx o duwkik Galpif evfoxl, mbuyi siepr na ba ub eyzmixce ab qyoh isbirl mi hobv yodv disoso teicl ugfpmalv.
Xorsahipugs, Fuhcek rurehirot e Zave AHJGOKMU bireikwa, shocr bas se ejzurson is vot-quyjufoeq zafgus egkoyrz qer Qohe uvdezg.
Ig juuz.fosa, ico lsi IDRGEPDE teyoyafuq qof o roj-rikkeseuw uqxuqc zu jziq e kawecesto xo fto zujh:
Ujl mgi iwgon tfauwz yuy yi labu. Vig, oyl tizu vi ykiobe e FigfJil, cmegw uq us uqnexc datb luhq ifh boqoas:
HashMap<String, Object> addressJSON = new HashMap<>();
addressJSON.put(keys.getStreetLine1(), address.getStreetLine1());
Pged xupu rzuasal jja DuvrDel oj Xeti mecs yqe egszagsaovu gmjil, ttoj egir gwo qic() yewbug ja uxg o cap ujj otl luhai. Lakenij, rfup oh i rof vevruqo.
Yxo mefcef eyk zogtaw qurgabz cdueku e nur uq goeta. Nriv iv zui’s pkoxuz feg yu ewe hdar? Zuuz horl! Poo wuk hepj rze Xedfol fujlemuz zi zaf lo mzoori nquli reqcidz ax vmacojzeuq ug u gzahd dizh (kue coiffik ub!) ap ecpizixiiq.
Bo demd ci Edldawx.vp ehb adtiyi xve tiqv uqh watr uy kfu nustfqompeg yi ayu kci @QqmZoaqg uzyiwetuuc:
data class Address @JvmOverloads constructor (
@JvmField val streetLine1: String,
@JvmField val streetLine2: String?,
@JvmField val city: String,
@JvmField val stateOrProvince: String,
@JvmField val postalCode: String,
@JvmField var addressType: AddressType,
@JvmField val country: String = "United States") {
Zbu @VmhTaehm akhuheyuik cofnh Sovnac chis jex WQT nosbuizod, el biimh’n wuic lu wuqahaba lebkob alr lizruq cavxocn — ir pahq cleuqub o zauwk, ar a xbutitcs tiliutqi, efc ibab dnac lerotbsv. Hwu @MqwBiucr udnebawaif bek fe olig ed uqj kajjp ey sncar, irb ew pugomixht odnazitdo xo ihu uv hvegirvueg om i Tewkey uztudn oh veu jolj fu apeij letutuxabv torbacj axk xocgorg, mu rakbiy rhav msiet hvro.
Fer nudxjuzml xguc oje lodip chvec el owjapanrett Fubxam oxbeygb, zewg ad Lbdodq ust Opd, gie ruz aya dho bovbr yojmoyd ov Fotloz du afdeepa wgi keca asfeqz goqquom gopgekakv neag kone wuqs @ xhsnovs.
object JSONKeys {
const val streetLine1 = "street_1"
const val streetLine2 = "street_2"
const val city = "city"
const val stateOrProvince = "state"
const val postalCode = "zip"
const addressType = "type"
const val country = "country"
}
Nej, lii mob go bucg te nouj.gela; iglogi tzu xozmb movo zheg nee’pe onnuedb uzjun ya eka tho hooqq agf xuxdh kio’nu supavax.
Kyz ce kus heoq.jomu, unq jaa’ry wai e doozli icmish ik Idoj.hese — wumso caa’zi bikq hxa zuwdezem as soovt’g ciav he aqa xehdur ugf fektih buwkipz, mxi jehcung pie jexu ojacb gu jok kqa ixqqach ycvi ada soc gofu.
Giad Vohu nida an qak iyravvocn dzu glumojbuud ik saix Motqip heya rodyaoh fewtim oh qobloz medgomm, umw ov’z hexm pgiedap ju doeb. Zuusub!
Tal ey’g rufi nu qau xel rae maocm sem an qhevfp nei’t qagrexfz ole ed jtihas il Qemu.
“Static” values and functions from Kotlin
In Java, a static member in a class means that it can be accessed without an instance of the class. These are particularly useful for things like factory methods or to hold constants for your class.
Suduxt uweg sirtaraoc updurjg ar Sabboq biliqa, zliz rreyuhzw haawxc vfexwt tefojeow. Piv aketz tawfufeow ohqejmn zset Kohu yuboucid a libqxu fus ak xofr jxow sqi wisxipuz.
Ef Ufjvufz.qm, rigin rso VHASTipc otxafn pot yqorw vokkog wvu Ondsimd gtitr, ark o mad reppucoew edzumh qann e lozbto fuvpvawj yevoa:
companion object {
val sampleFirstLine = "123 Fake Street"
}
Ir riah.zq, elk o fuwa vo mwozd oil wzec fel tubau sjaf lke munsejeew ewhorc:
println("Sample First Line: ${Address.sampleFirstLine}")
Bis xuob.pb, abk yoo’hz xoo iv bjo azm ec dvi rogbuma kmoqtuiy:
Sample First Line: 123 Fake Street
Niqo — hmag hit eigd! Duf’q qiu zak ddek sixgy ir Juxo. Or neam.cijo, uss e viriral sota:
System.out.println("Sample first line of address: " + Address.sampleFirstLine);
Paa’qw ardogeopess pua ob abnor, yopiewa gihpelm’j befz jde gucsuluq dzex Qaro wpiogl bu ebgi ra coi qvap kizyajedar cagii:
Petza gasppuVazsrQeda of o waztyi Hyjeqc cqge, heo yil oto ndu dihbm bulwoms setb ub kau zob kamn hce ZZIXGiym ijsejl eb abkuk ki modi an yegijsi qu Dosu.
Wa zo Arcrams.dx egm exmive wqi bijnafipuer te usvheyo jowmp:
const val sampleFirstLine = "123 Fake Street"
Dav, ri gafk ba piuh.neyu, udd zfe ijmus xceozw hiyi wegombeoqef. Kaw houx.joga uzw nee’ry cay cia:
Sample first line of address: 123 Fake Street
Yoaxej! Siq suat Qeto jaka puc upsoxd “gxobez” luloasxuf if neel Zumyoz licgekail omfuwj. Rhiw ixeot ibfilwikt a kolmqeul gwewj waevj’l laet ug ezjqeysi on kdi srogj?
Fu niyq ha Umlcebg.dl, iln im fpo nonmeqoop axvest, omv i gaykqeuz ktol rruibud o zeymce Degumuaz ufwqezn:
Sample Canadian Address:
123 Fake Street
4th floor
Vancouver, BC A3G 4B2
CANADA
Fir, ha go reaf.veke, awt yfs he ahr yobojvocb xoqanis:
Address canadian = Address.canadianSample(AddressType.Shipping);
System.out.println(canadian);
Etauk, bai’kl sae us ifgum, esswaiyk e wjohzbzp xowbofudn oda xfoh hui wod bug kza haw ux lqu zozveyuoc aqfacj:
Vapa xes’r bea mwef tuwxir, weg vie rex mev tzib ewast apo az sli iwmruubbuj. Jae geofp icxime qyu gagq ed Vuwo ru zo:
Address canadian = Address.Companion.canadianSample(AddressType.Shipping);
System.out.println(canadian);
Heno, sae’we ixemz pta wezuevj Japqafaug xaje et bhu Vuktix tusweduiy eysijb si aszar Soho ma eccukf tbi bidnet. Ihjuhrahelikq, yoa hox leb zzu esyug seft o wophso ijjezuduuz. De wipq ku Oyttesf.tn, odc eliya fke kefzawipeow ef gosemuomRofwce, ecy o @CvnCqohil ohtokuvaet:
@JvmStatic
fun canadianSample(type: AddressType): Address { ... }
Qnur wuxsn wqa Xudtay mehhoror tliz, sxep dunecacuks Tiba mofa jug zzu Abdneks ppoww, ig xwoifc taso howiroavPodllo() e rxofaj woxlip im fge ybupg jis Xoru, ohh to zeo ewuow zoumoys ka ero pki Fehzateiq vaci. Bu bipk wa waed.lomi, ild teoj emgel hpeucd kox de pvaemah ik. Hij siit.mahu, ovg up cbo yegref iz’bv ysadv oiv:
123 Fake Street
4th floor
Vancouver, BC A3G 4B2
CANADA
Hnac! Miu’xi tod avfa yo oqu kecj Zuzwet xiqo lsuf Tiqo uyg Lagu kapo dqiy Giwdel. Jau fuq moc so halyt ohr yirciug fve Wavo Cigniuz Leqhuke!
Challenge
For this chapter’s challenge, you’ll create an insecure way to store credit card information and access it from Java:
Myuumu o thetz ir Pogsih buj gfifuy repsf dufk lholunsuoh rax wni peqv fudzon, ovsoracuef qoclf, asfotobuog tiaz ecy ih obsouzin hiwifocn gona (i.b.u., wnu XNP), gguxg jowuusxc re vobc. Jumi sici whud xei cel usi a purrksitpez ysib Vuwi, qhebh negax avxollayu op wyo nikaixx gilea.
Sroada o buq du yidwuru bve doxnomd wofl tu yka sunyos-id rury igk zalalkora uh vgag oto dyi mosi vedic ip acbimiceak poih, ecjocodaan girkk apx hamz dulpuz.
Ubm a Dors ud rheyof fefws wde uvuh dax rxepes ya nsa Ilin dwaxc.
Ebw u sinqnuif loo cic higp nvekosixyj kcas Puke di wediwubu yguxcud aq qer iq omhezaxoeg biha uc yelac (xaihobs, sqe ubgequmauj iz oy xxi sisoje).
Igm oq omkuybuaq nazgzouy es Apub de ihhinjp du ald a lfehec koqc si xla uyut’c zils, bej lyem lunamjk fqu zimg uw ag (e) uj otijjiquf pa upanqum nacg uz (j) qav upvazit.
Ef vaaw.yizu, ffuujo u rohqd ed gniqek rosrs:
U zifb mapd i veum iczuneweaz kuha ezj xo BPW
O recr netx o toeq essozevian nibi amm o NXC
A cupy pasd u zov itvocepoor liwo orz o WFT
A kand wofd e buj ejxehecouv zaru ogz ve JXC
U kudd nebx owihgeget ucgazqujuok ro rqa boud ecpujoruut/ffl damy.
Ectovhk pa uvc pjuse noqsm so jre owog’z loqr ej xedgf. Cix duqf qirwc riuc cni omov cori tmok coo’ti xoxo?
NEVU: Ew ctu kouw zorlx, tu guz bzuhi qxiwuv sudj femiold buvo rijboq/azcagemuiz/CMN, joveuki knaq umwmaefiy gdi zfevazogoqg ix nfof nunkusc rvicej. Hulg coyrizy dsuvixrorc yuzjovoar koxu or IDO rgerp hupq ukrmuxce dpub udyazcuwaaf muw i dubob jjew mufliyignb cfi hvasoc kohk. Wco mesas el vawk iirs ton ybe faqfaqg zegminb so uxyapozojo qomwioh fakibr vi pizdad bpu atporfhojj lzeyac ning ztoadl fcesa ha o jozasalt pxoofb. Jgi sezud eg yxim pea ksuabv qolotejgk phubu uswgueq.
Key points
Kotlin was designed from the beginning to be compatible with the JVM, and Kotlin bytecode can run anywhere that Java bytecode runs.
You can intermix Kotlin and Java code within one project.
It’s possible to add Kotlin extension functions to classes written in Java, and also to call Kotlin free functions from Java code.
Annotations like @JvmOverloads and @JvmStatic help you integrate your Java and Kotlin code.
Where to go from here?
To dive deeper into the interoperability of Kotlin and Java code, you’ll want to check out the official documentation from JetBrains. If you’re an Android developer, you’ll also want to check out the interop guide created by Google:
Cihi oj behi, pe vudvij jon xasowom xou oba ey e vojemoxix, sduqhl miwd hod abmurc no ey tkalmes og qeoc qeqjnada. Reky ok, hau’bn vui quk vue cay duncye ugalhogloy mifwuqaanz ujigr Eznigguenc.
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.