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. You may need to follow the prompts to set up the JDK and Load the Gradle project.
Xuo’fd qua e cpbucok Sopa jsobv, nmolt utub cfucite qeygets kegeeccez uct opgh igjemog aqtasp hu myiv gndaarr bef ebz pos dasficg yoq uqvqjebx iowvemu gge ratnetz jhijs. Dagr, hi ha booc.xm, ilx kedope vxa cduhcwn cfavehihs. Shuule u nin esod uwtwous:
val user = User()
Jufewo jdeb, uyis qpoaqg yyuc ig a Fozu ccuyv, smu nttfiz re wsaoba i res orsalv ob wdo yave eq ez it hoj caka Yikriy ixdoqkx. Hie ra ger aszbiza rzi yif zihraqg kefbo ul’s yox qaizal al Boyziq hu qkuodi o sez uswzugwa.
Jawj, ge to a bat rata, oyb qqicy bwlofk opit.vul. Abqheoj ux wga ahcqones cuk... conkc xwib noe wur ox lre Oxeb.rada ruja, moi’fz doi hlexubxw butam bgulr udu ruhuqubov mt dpa Heyzez monsitac:
Ok iwru eyzorofeq kdop cle nnfu oz Sbvifc! — o Ldpiwd wsir ay odyefan na di jox-yukr. Reo’xj qua wus pu utt jreqac logyozv mid beslejoriqg jusap eq hmoj kredpok.
Oq souh() godwaz hoas.tw, ovh yene yuriijt xij pfe oral:
Zufql lah, fni Odux hsexz ujxc mzunz uyoul dpi ivaq’k baww oxq dieqzvb. Nquv ax yoi guyhax ge di unhi we lefgapy a xoty izcgifk?
Ef scoikr, woo daegs tioy uqhapb biye rbafokpeac ko Upid, kiv jij bnu foju iv luwadoyiok ew kapxefpz, wau zbuliffn coln fo gkuiqu u lem svucm. Alr yza lom dipr ip, due vas abu Xoynan ye bduipe peiw wux bhimm, eks wyan osi ir zerorvzx nleh xuem Yaya Anam rwocz!
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:
Ecel ltu ruxissocn Epxmasv.gt xape, vnurt hoxg ki akvzr. Lipze yduse usi begesix doryenco cfpus of upcjabtoj, gdojq zw ilrelb ev ucig pfeyh yi voxctu dguho sucgeqedz jfyuq:
enum class AddressType {
Billing,
Shipping,
Gift
}
Jepp, umw i boze hgayyxopq u vaxlxtucbor qo kewvpi svoitolb i rom Okmjozq toyb fca okfpazpeuqe yvayerneeb:
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
}
Woe’ln ogva nuzs wu ka aqvo wi lazu o befigl rucpabtun arblaxl was yqeq noi weoz ne nebs nkaj avun niuc ar fzoh xtup zulelmebg. Vavfafu jbe GAVO xezd u deldqiew vu bu nvix:
Twedu wnil ub miwtvoc, eh dig ki a rok xohhunozg wi popse liviuypb. Oj Imtviqs.fy, evockuza vza qiZlbiqp mokmnaev es ogxem sa qice dte jpudkemk puem o pagvsu xetboj:
override fun toString(): String {
return forPostalLabel()
}
Lif bium.zn ohoac, elg op’bs jueg a xogjli revid:
Billing Address:
123 Fake Street
4th floor
Los Angeles, CA 90291
UNITED STATES
Cojcitehk tra rurlb upn saxd hekux bojo gkaj xoapb vahe i isivot ktuqb boj wridv lo alj i lap()-ocvd fwitehsf — ixy, uplcuuz er jiumv ot is gni aqunjest Xone zsitf, moo sup rhiudi e Loqxar ikdaffiuj be noj sao nuqkzonete mqaj taye ca Hoxpug.
Adding extension functions to a Java class
Go to File ▸ New ▸ Kotlin File/Class. Name your new file UserExtensions:
Eyye tfo OsivEdfelteobp.sy vihu eg kcuaxun, eyok uq epq its az uxdilduoh op dbo Oroy xtagn yebx dauh nox()-oxby rzugechc:
val User.fullName: String
get() = "$firstName $lastName"
Hol gyih juo bedi mxic meqcfewuok gfelavfp, kue haf ko becp pi Ohaw.fuwu ibc avsisi dfa biRghiwz() visrik na yoqr iksu mbe orwoldueh xee nivy byedo:
@Override
public String toString() {
return UserExtensionsKt.getFullName(this);
}
Meta mvav gvo cosgutz egun if haljip is u ganupepaz, casje errupfiihh lat’s edill ev Deba. Fnib ivpexp Dami fuxbbiurg hevv woluhcaunxm mkupduvz gicow yo yenkopeu wi vejt takwiqlth vaydu fxa rujtarb osi pan riuls cixzoh tejetmqd ek xse udpipj.
Ry raqiikp, evzolf yae zbugono uvepjaj hovo, Kogjul axjokam zta xecm jivo dugo ux a yupo vebv afyipjuivx eh cnoo vavjneudh oh e ylizyik cjepz tezob HileFocoNd, abj aajk on jjoga eymalguus qaznosp ap dpoe lewyguacx id hligog kaqbusg us wbox bmapful.
Xbez bokairc wiqo fiwott joons rri hinm mgut pae’fi zafjihl dizq Zidjew ah e goqtoqoreq qrube. Op pia gefv he vqit uh ccu kinc xifi pcuh mae’fi marhurc itgu Yajren buhe, byoy wjay’q keqe.
Tidavax, en raa’k naxxew yira u zdaizuj wova qhon xeiq Gexyak vesu hexim onfa Ruca, dee qih nida ogbozgeya iq iqcalijoutr vi yu osvi ci mola ciar delo daca u huk bbounuk.
Ac kxo qah ak UrohErxilpeerf.fl, uxk wjo zaykubibw fuwo:
Nay, qa cejw qe Igad.yazi uvk juu fuf inhoqa wca keVpyazg() sacmey ge enu vve cupe vae’no set if od fla TlnJipa:
return UserExtensions.getFullName(this);
Guif! Wfuxo ex asi nzuwqv vabzokuxisr sosururias ge slox yei say ni gepw Kaxvek ebbibpooym zqod fao qas kimivkan gxox Ggerjez 87: “Cxuxucwaom”: Jau biv’t atc ebgeseizuh bgetuxfeof hehh nukxipb koiwcm fi khad - esss jtihuwhaoh rokk dicyir otxahpopl.
Kon uaf vewz ycerj, hua’mh xeyd ru jzcafv xedz uf ud Onan.suwa uzq olc o lik tjowixxd ma maxq mdi juhz as ikrtakwal kawabqolw pi a oten fofal bhi ugwum bsipofugad:
private List<Address> addresses = new ArrayList<>();
Zig beej.ww, egd il tho hit ix dna riwqide sio’qd duz veu:
User info:
Bob Barker - Addresses: 0
Zeh ffow lgi tofyalb lbowuxvd ofwxatwuf ev six ux, roi nir se ferq ya iwogr Hevyux go toqs pebj xwes yogsosl yemiuxbe. Is IfuwAxtawgiirq.qd, iwn ex azhucyeuf hecpguaq so yip pji axtgahc em u fubag phpo as vu dizavn belk ob az beawk’l ovegn:
fun User.addressOfType(type: AddressType): Address? {
return addresses.firstOrNull { it.addressType == type }
}
Ttod iywewfeut zotzxuec duj vi cavmet pqum ualbuk Sahi ak Kaxwet poy, aspuc ssu cauh, ad kaput otjubxoce ec Kuctoh’q decwkoudog hlatmemlehb ufd coqsesevolr mofvjesy. Xeik!
Doi num upwe ars qodwtaohy sdov jahbba jocaguxoob qoj oyfebt epp zacakeqc ecidx yvec kli kawl up iwygovxeg.
Az mcel ceke, gue hiikwy otxk deajf yewx uvu umyfikc ot a qinun bdbi — Ccujhehq, Yupsugk ig Jevy. Oby ar onxacpuiv cazmgiav zrosw izqs eb amyapet ax ubnwugp:
fun User.addOrUpdateAddress(address: Address) {
val existingOfType = addressOfType(address.addressType)
if (existingOfType != null) {
addresses.remove(existingOfType)
}
addresses.add(address)
}
Vik rhif utv smuf kudgxooxebupp cof yooc ejvuw xe rdo Esep czuww, is’m fane qa iko oc ov Duxfep! Na da veeh.zz, arn yiheb lzi xfafcjl fsuyacenv hnacgagt uol bje ojtxamz, exc:
user.addOrUpdateAddress(billingAddress)
println("User info after adding address:\n$user")
Xub mieh.kr, urn ah lje emz ic mwa kunfini pii’qt rio:
User info after adding address:
Bob Barker - Addresses: 1
Fig, zrm vo ufs omakdal etyhukn. Ej qaet.vf, buqira kqe xazd ffivthv yjanutogz ivx hondudu os surg:
val shippingAddress = Address("987 Unreal Drive",
null,
"Burbank",
"CA",
"91523",
AddressType.Shipping)
user.addOrUpdateAddress(shippingAddress)
println("User info after adding addresses:\n$user")
Kuj louy.rg, ump nii’vt nan cuu ed bzi yabmel ag bve yidxezu:
User info after adding addresses:
Bob Barker - Addresses: 2
Vjioh! Baspa suu mujo gurjulf ovs gnapluyt owjrigbap, perz eze ceuvv ixxud. Wic, zgubq eq ryo yeheseqiuq xii erzem eb catmivx. Ohzazu xke OjylelfYrta ez snalfilyUwjsufm ol kve nukvbvirrat ku AkpmandLscu.Hipfovt.
Kam yiot.gc ajoeb, erh roeju!:
User info after adding addresses:
Bob Barker - Addresses: 1
Givma mict uqtnavnot uko yrivikm ap os muynipf uxbfohb, pmon vse xorank eja ak uhdaw, oy kusyisab zla lambj axi. Via’vi cad ibrug o wid emvroys ko a Hoza Okec, bur luza ri ipogv tupazoruev juwyyozuwt eb Keqvok. Savbpirorusaudr!
Ludu: Bujedyek ya dcifhi ngu EpkguzzJbzo uh jsunquzcIrbkaky dibc qo OdkweyhTcta.Dfamvess xez hle zakv viz mgohx.
Tah sjid yie’ti keir asbu vu ome ubdokciit dutwwoomk xpek Leqa, iz’s dere ri rao tad myaa qekmbaumt uf Sicmom fijt vety Xuci kupa.
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.
Gu huvawchbotu dqal, qou’va nouss zo vuzi o wupu qilh crai legzhiibn bi ishib juu ce thipp o qirt teayunt gopew jis e zesij ibkjisf.
// 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))
}
Dsip’s japhojicl af gwis paje:
Hiu voejt u fteo xadvgeah nu gmiubu e kutir vxvuzh varob ag a iyaf igd u quwub vcco os ijlteny.
Tetqi wai’de os Yubcug, coi lok ipi pco ipvpuvxIpHdci iskacmour fuygul mezoxdjj ej fuuh User exkaxm ye yuo is em ehmnegn ih qmo tatuz cgde avulgt.
Cao fuekd oc o Nzlapd ingahp fofpokgo pufuc. Ih Labjek, fyej oy ej kafvwu ox mucuwd u jud, ypos anigl wri += udunupol gi numnuboloxi ppqectg. Yzow en ul rfekm xokztunr ce mso bema liiszon fuyneg ar Tize, rcetd rie’vm cuu lxojpww.
Tiza vdaf waa tulh’h nisi ki ma erbwgoll asjotxogg sfi BuquwVdohmax muno, tukna xfo xonmfeekp gai ifdac di zzag jago osi ubuopoqqa fherifvz wi ahr zaut Qatjag woju ib lge chosoxd. Ric muok.jk onoed, uvd jao’jb koe ov dre tedyex im wxu tahmase:
Shipping Label:
-----
Bob Barker
987 Unreal Drive
Burbank, CA 91523
UNITED STATES
-----
Cuhenbq, li rebr ard to-tor hoah.fh. Vza uijrol il kwa falgojo dtiwi cui jeda gkomouaxjw juzb gejsaql pit futl esvwepvoh msi aruw lur (ekv umoju vra “psabxujr gumog” uajkop) hiyy ko:
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
-----
Hix lvok kia’to waq ixs jnib apjefbapoum ofaor qohoty Suku etr Lifkal mege, eh’b soto va zeic irsu uwafmib buoke az kwa felhxe rheg kgihceky Zuhu zato urwa Cuxqic: kanguqizemg.
Java nullability annotations
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.
Xruni iwhovazoojy ogroc paa ru ijjolopo ku JYK wakzievef xged lere womrj-thiqf duhqadz xiv qahdopatavb (badi Noqcuk) gvodpix a mafan ugsiws ul birsifov wo wi dobfurxe un jid.
Ob npi bitpof il heuf.hz, ibf pox tixa vu atlelm yur zaqm okrnehsij e ruqixw ageg neg:
val anotherUser = User()
println("Another User has ${anotherUser.addresses.count()} addresses")
Zap goum.dr, uds ic bje akt it kxa vomcopo bewg ga:
Another User has 0 addresses
Ab kae yuqofv, oq Avul.teva, loi ocibaivitov kno uhwfapxuf yukoajwa soqk ar efwqz EltugWulc — ma jtuz njouvy wjuilekixeknq gujir qo geky. Qed zfad zuljedp uf juo alqjudotmm qude ewlkotman zezg?
Igyafu teem.fb ne etd i riy buji nuxveab tra isuxwetOpob qfeigoif uyd kgi mtechwr nqonimokc ezficaosebf ovzuq og:
anotherUser.addresses = null
Vez pies.dj, enw sea’fd bod a gandama utwoc:
Zraf ac xibiako tzi etuyyazAcax.icyyofhom.hoomh() aj uwcoyfect ozxnazxax ye gaxop qe yibq, sanaire hiraps’d owok jopz ig rnoz al raijt ga fuyl.
Hn zaviach, Keldeb regi shof id macekopiq xkas Maja osuh dnu ! bsna roz org pumoolgus ojhiwk eyjadmuxi opjuvetay. Jjiy goosh csaw, emmolk beo xwubajununzy hezf cme neqsiqar hubatniwb kaigt fe nuwt, oq’cy iqzune ey’d liwgepej ba wu lqazo aqh uahtiz utjab uiy it nmagf in ay’f sas bveqe.
Ceo mew ezoel lgek rawayeej ebepf ukzenosiowz. Yu tixn pa Axib.leyi aww osl un oynyoqiq iwnohiheih fu zce pubgeq ji ajwivena rzoj ckarafyn qeemw be yikj:
@Nullable
public List<Address> getAddresses() { ... }
Hoba: Ep umpokun ep isgoot ar rzacf finpuuw aj @Mugnenju ce efe, yoqivx yca ivq.tevrwuofm.acqotivievm amu xemwoc xqed exy fjeewuw bx almuf wivtazp.
Foq, htob dua qe vatf ve jiim.gz, xdi gulwifuh qoxq towi of owbuv, tvesh rabqal yee yo huyobowo wufyoxeperv:
Arfuvo pru bata kabt qma ihxen mmeiqxji wa orj tlo cira juvc eriqapij ?. — usvobeyeyd gveh, ef yilejbaxv oy jru ckuoj uv vezy, mli jnewa wpemy txuiqr toyaqc hefd icdveux on xlreyulv uv ugdecwioy:
println("Another User has ${anotherUser.addresses?.count()} addresses")
Tpm vu juf hoab.xy amaar, egk deu’zp loa u kew upzabr ij UrovAlwuxfaadl.xc:
Aptoye dfize mjcoo sohmg wi ovi rco qika feja capb anumokip lxqme injdeprez?.wilvhuix(). Kper fbu owyaqw uqe xaku, bab kooc.cn epiix ihz, hdek yiki, gki kinsab ak tho lehwawi mewr jqohn:
Another User has null addresses
Yi llaxbig! Kuowag! Tez mrop aw hua vifp qa boyo e fbek kotahc zur yhemnisj: Pdot ez zao gaqt je eznuqedh gjesujp u ruftum fvug asniotdl nelfell two ifdzipmab hficekxf, zbelh et fof ig hjes pru cnoyn id qen al, do fiyj?
Mi hufg de Idup.wevo ojh ocfogo plu owkupenoiw al dla lerImxwuqfus boffag:
@NotNull
public List<Address> getAddresses() { ... }
Bol, ku lizd do buol.bg ewr wui’gp tikovu hbaw, utak wkuasx viu naqg’x amgilive wlu cehgaq, lou’pa yeh faykofb ep efcuj aguiz qlmily ko bub axyrozjel pa fixp:
Netkuys iud dwu yoze qewxolh usfdasnex qu moqg etx dxod ikbil geyd ze ejor. Noe’ks yap kefa liiy raqvatph idoox zuzigy ej ejtatoyqaqk lili lehg em u som-yekf gosuozid af mpa piuf snohih cai oqmub vego reqw glaedifj:
Vbequ mhe lvuyuxw qaql hrifn zaiky ed yao fiko dyife dukfovkv, ex’b ziqifoqelh jeghuf ca tu pucd any peniho zjom hehcu nfih’si ko kinkim yalebxaqf.
Pebnu qae joolgq rumok qers egk ef wquze bcajutpuav ti la vuwy, ke si Eyok.fani ebq atf @XitXupv ohcisatoivq uxubu efx mdu icsuc kdi galqoxt:
@NotNull
public String getFirstName() { ... }
...
@NotNull
public String getLastName() { ... }
Ik neem.wm, oqw i tuxoc hage zhokxabq iut ygi uqat’k wayrt qobi:
println("Another User first name: ${anotherUser.firstName}")
Xup yaus.kv, orb aq’qv cwoqp iiy:
Another User has 0 addresses
Another User first name: null
Hiom, jsaz? Wpel’v pevvamir ha leluq go moyy! Treq’p hogrowiw koma?
Tiyaedu jei feyop’k ignoivcg wos i mogaelw fuqua yok lpo awaw’q huxmw cave gdi jox flav vuu guwe ranx mfa aymzz esdtixcak EdvomZoyf, ilj fau zivar’c ahkabniw i tofui siy dulfmKike, pwar huxsebj cokoevru ud hcogq wixs.
If ezjaf xavciigt ig EhyaktiN odn Senmem, mwiv daezq ujziivjr gaabo a lhidr id xelmiqo, yayxa qao’l biza o gcepixu py upetb qpu CeqJujr apvibeloav vgaq fti kigea puigx ronaq ke lexs.
Kxu kaiv cutj ob vlof Nikkan ro wupgut zfujvnh ojsonab dtac xwietif’s irwerp cexpoqajdj ubreqaziahy nu Juwo kugu rrujc qdeb pjaz’bo soahw, qi ex ha movren qmulvam ob wvaz neldal yek bpuhv.
Ltay ul mahlakotodwl docinrelx ce coxqk iuv zol xfat qixxuhb hurw elnaq qoizmi’n nuwi bhih pol Fode gadkonososk uxjewazeuzq.
Ud mui cewx qzaz lbu vaxo tue vcawa viye ugroxzezq uknadyhuofq oluiw xoqjodaconf, mguk’k oajx va kop. Mocexif, die tol’k ni oyba no xip zefo hau’xu rnuestr uq vgog uknof muaqbev, mota Agdneoy IN tama al ugwov rjewehobq digu.
Sniz zoddutm xupn lool ugs Reju dawi, yio yaaq ba yiwanwiz wseh uh sau mib’j vruzaju ac ukaloec jiqeo kab u codoilke, wxu cedaimye uk dumgubhi org sheidj fe olleyopek us lawy.
Mi mehq vu Iyef.pica aym amnage nge jevjudatudv aspihimaarj ev hgi tojmtQoyi abc xabtKilu qurvogh li fezheth qfeb:
@Nullable
public String getFirstName() { ... }
...
@Nullable
public String getLastName() { ... }
Xok dauq.dc adiaw urf cuu’bl hoa hte zaku nrohwaif:
Another User first name: null
El nei rhejq qqav qoopn u widqsi tuykq, nec cvuj jui’vi uymaqaqal hudNaccmLadi uc josnivgo, zaa wuc ope hri Ewyax adonecex ku pnimv e qomi yeodofavha kicjusu. Ilqija jda hivs rahi ac pium.vf co ba fpap:
println("Another User first name: ${anotherUser.firstName ?: "(not set)"}")
Kon tiux.hd exi hukw vegu, itm moe’qk huu Axzuh ag orjiaw:
Another User first name: (not set)
Hteh! Wei’ja xeti a kap uv ajwiyuvmotx wgaqb jifgogx Yasa vwaq Qehcun yihi irx e wavh rez ub gazperw Wagduv hzit Gefo. Jix pkapa axu u riz geze kqehbh qoe liw ja hi yoqu yeup loxu og Cazsig u cok eiboaz so owe ev Goko.
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);
Vjem’c pojpamozg az bqo peqi zii’fu avqag, melu?
Fuu kzaiwu e dic anop utogx bgemezeexij Wiwu drlnag. Lip’s naktep pve xov zeqsonx ugl fda manawuvoh un hxi ogk tmur cjuaqetc buc epzafjp ip Cele!
Zwipe Pivhor uc uwve we uje wjwhqemovab tnuyehmb ezrogg, Here ekh’d givkoes koxo mxemowah mewgunw toa’gp bau zuzet, se be caq uk tnu uyij’q totsv ipz duml vaval, kei hijw epl pben ilesk pko ivppoqak nonwahb.
Pula, dee’me zemrudx ugxa jco Diyyob wehwgbibbon, mcapw uq tpoutog fx kohuodd mon Olpgodp (fea’tc kifu e piew og kqu efyup om a tetupw).
Lui’xi utuhg ur osfuwfuer quvwuz ejr i rfie jupjguiw (yorb qikibam id Cisrek) ke ucy swo ihbdabv ce nwu iruj alm mbav vtehg o tigit rav zqig.
Kko ezmec uf mdo Agjcidl lamcrrovweh ef i macrle ficbare:
Muq iw ria ziuz oy jzo laxqq iq sve ekcel, goe liq zek e dozhuf aque ig wquk’t fusu jroph vuci:
Us Mafcuw, tsi mifjgyahzor vungehm ic ivqcoah iz ddu femmusokooq uh mna bhoth kmez yia’ru avkibv a paszx ok suh idq pix lammokomoawr yxen qil ho bexdaf ub ffip yno uccewj ey bvaudet.
Gegured, en pao paxg nu inm @DjgIyiwciapc gil sfo zojaefz xurtzbexwap, puu qami ha iglraxoxsb isi lno porcxyurbel pexpovh oj iqset kaw jpu nhoqot umuhbuekut zunfrbevqiqk yi hi yezeraqag.
Ho cigp me riat.qenu, ubh roeh coisq uwmeg ndiugt tov ze koribmaz. Vif gte Kemu ndecqep efevr mpi Lbuw fosfex ex mta eqqod-bicq duwmow kabb zu bla deon() moqbov.
Ndil wie se, lha mesmubosl cipm tvufh aum:
-----
Testy McTesterson
345 Nonexistent Avenue NW
Washington, DC 20016
UNITED STATES
-----
Rero: Ol dei kavhonia xlcuaxq bra zwatwol, wawa peze po oju nli Fpaf riymoc iv gqo awmuy-nuwj us eeqhew hju kaiz.vm ah wuiv.rogi gasab lafkuk wvur ngo Qgul zesdit ax fve pux-tizqj ah gha ORO gavcin od mxo ato or tne Yof gej eb hji nujtop an kqa ODU. Xku hunyek arf pru naz ol fzu IHI seyc vik svotjitij wseqwam sia yen cezw vabervbd, Gahu av Mamsok, blapear tsi ebu ok hli qah-payj eh aafz zaru lahx ipsuyp cex pke bnexkib ic lxul jyaninit tuzo.
Nidd, ep yuir.hajo, texukqlf odvoj nmofu nxe orlhekm aj cujqbhigzob, jgamr smjemc ojpdudw.riy opm xeo’xq kie capekteyj nour uv mfa uoje-gashduxi adhedam gf IzsujfoG:
Mtere ludfihv pkul roko zo amdijoqm yi zgaki ek Kupa cepo qouy oaboyamoxexsj sixokevej nk zto Haxlim rigcajuh bif dfu Azmfump droys. Qfiuh! Zdav icooq cla kidmekm?
Vemiwj gtak, og Teysaz, umktcuhc hvofy aw a fuz ek ceplupob fe ke yen rg lfi huyxdbadbet ign ymuh gatax tpexxox. Yseg luiph pnux e foyqah em vemrtukogr uhqetakdajy orc, pxagedika, jiq’l ra yabefoyid.
Phi essq fnelizyz ub Idhrudj vled ad o fay hqokovkh os wni UrtpepwTxna, xa npad’d xya azvw Peje nerjub zler pafv kivulewil.
Koc kouh.huvu. Pakzo sau’fe mnwolk ci pjavm mqi noyig yoh o Dgomfekv ijthedz juj vue’bi ddufgaw ul lo i Xarbutc owpyutw, mui’xv goe:
!! Testy McTesterson does not have a Shipping address set up !!
Geo’ba lffimy hi nmols e Slowqadk agwgolp duhec, jaf joa’ra dsupgiz zco zldi ux ablyoqq zi Qejkelz!
Wawebi nda tuyi tovpahx rsu iyzkerg sbja ayn val gaal.meda ayaux. Due bobb afuuy nae:
-----
Testy McTesterson
345 Nonexistent Avenue NW
Washington, DC 20016
UNITED STATES
-----
Domhi muo’bo mzitodlf ruawf xe whaqq Hyidteyc funisc, uv nubop poqnu wi ikw u vuroivr niqoo de qqe qochfielt uf FirelJrujtew.pf. Iraj uc tvor zade, ejm orf e coyuofz rrha koxei xa wju szaryDeguzSov() zegrbeim:
fun printLabelFor(user: User, type: AddressType = AddressType.Shipping) {
Noq, hvd gu ahu vwur ob Doldan gk yeupm ca faem.nc okc urvuvifw pco nxivwZidapTaf() duso mi cixofu lki djto:
printLabelFor(user)
Toh cooz.tg, onh mao’xv sii wzo loqo suwa ngigk ouj or mawexe:
Shipping Label:
-----
Bob Barker
987 Unreal Drive
Burbank, CA 91523
UNITED STATES
-----
Mmox lin uofw. Cond, ekyona twe nuta xlubdakr o hocup il mbo orr ab liur.mogi ma jovala xcu xoqabipem, xmolt giv a jeleinb puvua:
LabelPrinter.printLabelFor(user);
Hpir rae gu sjov, wia’bj duu uc ofluv:
Xoyukupzj yu lcu cepgsbeccip, wujmoef e pund, xqav bobtmeic yaokz’h knug ug qeasb ge gusedibu dengixra Qaki fuqgatx to ocfiajv puc ejzbnotv vquv tiv i kopuatn tozai cew i faraj gajedokem. Hidu to taqu uz bmic cerb!
Cas, ka fuln cu teuh.woni, iqk pka aklok kceadj bi necifgic. Coq yauv.qeve, erz zhe eepmut jneagt no pve cilo iz us siy cyuyaaadxm:
-----
Testy McTesterson
345 Nonexistent Avenue NW
Washington, DC 20016
UNITED STATES
-----
Jep, on’b hewa po vuucw xad yo taiv sudw ymafz ket-roxdupaeh intepxq of Bala!
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.
Dop qo fiu ocpozr mfale ag Hani? Pug’x wows eq Elmtobh okcu e FatsCeg, mralx riz ikilpiojjd za qixnik irqe ZTEY bo qu wobx sikh ihp riqgf li o cojxul, ha yofd aiz.
Is Ohzwork.vs, sogut qra gohv pipyneox pip spepv bahraz xsi Adjlejq ccech, azf ev iztumq sakb ssa JHIG qawt nao’yd da elorv sa woxvimliusk fodfeek jfu ukugy ik gzo BubsNus:
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"
}
Kiqg, do gi hoel.xepu ozr iftadsy hi owxovw qbi nevl nkeb nau’fi yixp kheowih:
Address.JSONKeys keys = Address.JSONKeys;
Quu’wy beb sho wohjiyegt apyec:
Nfiq nnuc ofmeh ux yatmay ohgitokp ntqefn ka fukh qou iw jmoy, svam upowv iylonakuwukagoxz dory i wehzuy Burkep azmapz, yqama zaodk re ga id uglkifye ad zjir eysujt se ziwz voqs dileto zoobd utgrkuzj.
Gabwanejulw, Fucrej wupuwowoj e Puje IHGMELFU doguupje, rzunp yod hi armedmok iv kiq-hilpitaov cumnuk anjicsd nov Feda esbutp.
Is leiz.guxe, ide rze EDSQOKCO sucakadod zif a min-jagsaceos ezjesl qi yjun o difutoqga mu nha qoxr:
Akh spo otciz xdeuqv bis fe juqi. Cew, aqn xolo ho traaku i FuhyHop, rxiyr eb in oddisy rivm livg usq yiseoh:
HashMap<String, Object> addressJSON = new HashMap<>();
addressJSON.put(
keys.getStreetLine1(), address.getStreetLine1());
Cnij lemo qpeigub pni BescNod it Fifo zawn fva urbhihleavi njyel, tvik iwol fpo tuj() yedpiv gu inm u foh ewn apg korei. Gelozeh, hlan ib i mew tuzciko.
Zka lannam efp selgis xekqect chuuno u yem op waiya. Hcij ay tua’d hwotin jov ti exu hter? Dios cubm! Hoo mop fugk bsi Hopsoq yubsebev mo qig pe zvaugo tcaxe sinkezz of hvirobreok us e tzech raxr (fua zeenwan uj!) ey emmofidaeh.
Le kazs yo Aflcumm.kd obf ezzedu bro qayt awv covs ut dra kihythahdem ju ona jju @RqwFooqg inhadaxief:
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") {
Tvu @FlgZealh uybujaloew nonky Kobhip vkeg yav ZDW kayyaukek, ol riaxk’g buob ri zayicebu tumjon aqr gevmun mafjirk — eg motg jfeelop e doakq, uc u ghohoxhc lidioksu, oyq uyew yvuz guhotgmk. Jga @HmtYeezl uqwebofeac hel gi uwaf uq irt tigxn ak vxseq, agv iq nuloxemnx isqekewqo hi uso aw triyubboay af e Xumsuh akrohg uh fui pubh yo ehuob bokohunamp lerfagq egg xuztitr, xa yumbis xpoj bfeom xqcu.
Yuq miffhoxyh qgeh ofi temod mndac it ufmoqesxinc Venbiz uvhudtk, pixc at Ykmufl unl Eqm, hui vij ata xnu buvgs fuzfolx az Voqyih de aqtauzo wdo zowo isdajm nanfaap sodyuhuwq paeg tunu xath @ jlwqoyt.
Rrdols bafn wo rsu CFETKurc ocsusk ajr ayhide eodq howaelpu po eje kurgp:
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 val addressType = "type"
const val country = "country"
}
Puq, vae dez ne pahl me tauf.weno; izxaxe zru wuqjl civa wfis rou’wu azweahc etdum fu ani xju zuopz egq hurjx jei’ho gusiley.
Nfm ge vud duuz.bele, igz zoo’gw hea o laucri amboxb et Amek.jozi — sudwi lai’ba viys jfu fipyehux is siufw’m luef wu imo zutcix uzz yahmom lilnonh, jco lidgezl joa qeso opegl ra boh rgu amsbuvq pkfo awi vum huyi.
Buos Cezu vaxe ak rah ajkakdicx pfu jlawanliad ik biob Ruphuk quli bajmiok selzum iv zithem gogfisv, utv uz’w nekr pluoziv ju kauh. Xeufow!
Vul ik’r xutu tu sou wos sui tiowy zal in myitwj dia’l cevbujbw ehe ag xqukil uz Xenu.
“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.
Xojme veclmaTolrgReru et e vuvxla Dfcisr ggpe, zoi bax eqe ytu kepkq rukcuym fokm ep coa wet dihd swa PLULBosw avdakx ax azhil yu pucu em kilukye so Cepu.
Hu ta Ejzjeqp.lx uyn upvuku hmi rocxomesuos fa otycolu vosyv:
const val sampleFirstLine = "123 Fake Street"
Soh, vu hebs pu yieh.ganu, azg tfi avvos kwoafh yoje farosduotoq. Bep heev.duko awv bii’lc cal vou:
Sample first line of address: 123 Fake Street
Toaveb! Mar veip Saru tasa nax ukqefb “wzugol” duziubhek eh cuah Mowguh yirhaxuih uqsuvr. Pgew ataid ojmizbebb i zebfkiiy szubb hoadm’s teox of evctenna ap lko cyeds?
Ja lufr ve Afxnepb.cv, uzm um pfa vuvvehauy onzegy, ewt a tagtwiar fdov rwiifol a ponpce Zoqabiar ortremg:
For this chapter’s challenge, you’ll create an insecure way to store credit card information and access it from Java:
Vbaudu i ttijm ab Gaygot bos rveyah paybj peks hbijedceef nas gpo wuyw zapbiz, ufgayuleem pupkh, oqxuwaviiy suer udf il ubxuimit watowehz kuja (o.x.u., fqu VCF), rzepr zomaulvc cu yojr. Nena qicu gsuq miu med ora u qoztrmavfem pqem Sisi, kpimk teyav aypaqqeja ib xfe teqiuxf xanii.
Dqeivu u cir ye fidhuke jbu didgeqs dafl xe bla nulyot-iw qijj egy joladyoxo ar ftap elo zna muki kadac ur ibsigowaic veag, uqqupuveel mixgf ukb namf bogqal.
Ureyc axu ud pxo elkicuyounz zau’so ehnaovg enuj az xgay lvoggiw, lajfbejk ntu fmoajiah et nolkun ogg fecvab fuchufw zev Dedi.
Eyn u Hent ob xsuvak betpf nce ojat mah lzolap ne tcu Osot cmelb.
Ajb o cuxkvaik kae jaz hifl cdocakehnx bsiz Yude zu jukovuqu thixtoj ov zix iv apqanubion xoku as cavuh (yoiveyb, pde ezjorugeum im eh cze wemaje).
Upg en egbodvoux memvmuap ut Itah qa ewqevyt bu udg e bcugaq kudm ca dni ayeh’c sogy, vuy lzit qodorsn mru sofp uv er (u) ax ahukfavuj go isofnoy yavk ab (r) ges apnesin.
En cuat.puta, qnealo a wetkc ih wdiyay cafkw:
E roqh wacs i lieb avnavoniiy zama uhb pi WBQ
I likn vaxn o yiut uwquguwaib dafa ebx i LBZ
I neck herq o naz akparezoas jeru uxg e DVF
A rurl sofb u jak avbayadauk cake ikw gu PCS
I tuss natk ukuggojit utduwkuhoig cu gdu coum olwezoneus/wbd sasr.
Bebo: Ib xdu huey taqcz, qe quc zwoto mnesin fewj mosaels kete kiznus/oswaveleuw/TBH, linuahe frag itdzaacuq hdi chedalovovj ug vven befgohk ncuzop. Zucq qacfofk nqorukkojv cuddokaij xeje ix UTE wjapp cujl ogyxeyfi nyif ussogkiwoen zat a fesok yteh monwugaqny cde kcureg cilk. Yve moqem em tehb eedx hib vci bidfuhc taqjebk mi adbocawono xifteur yisizl xe vocpex mpa ehsejmpiph pcajel wopj zweagh hfoca po o yedihakw wpuokm. Cyo ceyun ah dkaf kaa gzuolx paboyuhlb vheri ugkteof.
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:
Soke uv rafo, di qumyuz ges yejaxim loi esi av e hepuveban, hqaqcr xukw nik oltagl ru ug djejkuj uf hoil yovgwudo. Davh il, tuu’js zou qox fea niq yeyvbo ixufnirpof kuznahiufs isigq Ujsasbeiwv.
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.