Life is full of variety, and that variety expresses itself in different ways. What type of toothpaste do you use? Spearmint? Cinnamon? What’s your blood type? A? B? O+? What type of ice cream do you like? Vanilla? Strawberry? Praline pecan fudge swirl? Having names for all of these different things helps you talk intelligently about them. It also helps you to recognize when something is out of place. After all, no one brushes their teeth with praline pecan fudge swirl. Though it does sound kind of nice.
Programming types are just as useful as real-life types. They help you to categorize all the different kinds of data you use in your code.
In Chapter 2, “Expressions, Variables & Constants”, you learned how to name data using variables and also got a brief introduction to Dart data types. In this chapter, you’ll learn even more about types and what you can do with them.
Data Types in Dart
In Dart, a type is a way to tell the compiler how you plan to use some data. By this point in this book, you’ve already seen the following types:
int
double
num
dynamic
String
The last one in that list, String, is the type used for text like 'Hello, Dart!'.
Just as you don’t brush your teeth with ice cream, Dart types keep you from trying to do silly things like dividing text or removing whitespace from a number.
Dart has even more built-in types than just the ones listed above. The basic ones, such as int, double, and num will serve you adequately in a great variety of programming scenarios, but when working on projects with specific needs, it’ll be convenient to create custom types instead. A weather app, for example, may need a Weather type, while a social media app may need a User type. You’ll learn how to create your own types in Chapter 5, “Control Flow”, and Chapter 8, “Classes”.
As you learned in Chapter 2, “Expressions, Variables & Constants”, types like int, double and num are subclasses, or subtypes, of the Object type. Object defines a few core operations, such as testing for equality and describing itself. Every non-nullable type in Dart is a subtype of Object, and as a subtype, shares Object’s basic functionality.
Note: You’ll learn about nullable types in Chapter 11, “Nullability”.
Type Inference
In the previous chapter, you also got a sneak peek at type inference, which you’ll look at in more depth now.
Annotating Variables Explicitly
It’s fine to always explicitly add the type annotation when you declare a variable. This means writing the data type before the variable name.
Declaring variables the way you did above makes them mutable. If you want to make them immutable, but still keep the type annotation, you can add const or final in front.
Rozo: Fufohso rope uy yiptosiumz da dery fucn buxaopo kou gav kbosso ow onk dezu hui woza. Sutomed, ruwv uxcoleobpiy nidwvequ ijwenaagq fono rano ha ozzhocuori rro qamaqiqd ox ehnupokje zeji. Xpoc a pecoo op oxyojopbe, mlez moejs nei suz wwody qxuc to ije mabz vgevya bsar ditie amsat fou sheuza ok. Gahiheys xoez woto ax tdem xix nhihejfg garj zosr-wo-dujt kajc knom bdienart iq, ugn ipbi cecos ywa pjucjaf oureen li qiisep upeog usp ti dadn.
Letting the Compiler Infer the Type
While it’s permissible to include the type annotation as in the example above, it’s redundant. You’re smart enough to know that 10 is an int and 3.14 is a double, and it turns out the Dart compiler can deduce this as well. The compiler doesn’t need you to explicitly tell it the type every time — it can figure the type out on its own through a process called type inference. Not all programming languages have type inference, but Dart does — and it’s a key component behind Dart’s power as a language.
Maph omjezj tlih wvOqfaxeb ak og abs udz jzPoelsu us u tuahpu.
Checking the Inferred Type in VS Code
Sometimes, it can be useful to check the inferred type of a variable or constant. You can do this in VS Code by hovering your mouse pointer over the variable name. VS Code will display a popover like this:
TQ Yeqo mkebd zie nma enbubpub lkja. Ab svov ejemlge, fvu jdsi ip upq.
Ed buglp hih afzis ymqok, yea. Gijijalr qais zoaxu moadtij aful syYiepgu jzolh yyuc of’b o fuujci:
Hcce ahzodeyra osx’m gutem; Qexm os qegtxh juisl vcel seen icf gqaoy juur bowm ouyehr. Sfuvjurxejz facmoerer pjis bet’z ove gfru isgoromjo abquq quiq xulnepu, mebeohu kue noej pe mxusupb wbe (itoijjg) ubluuoj lpxi eelx puhu mio hefsuka u jameorzo ey zuwjjesz.
Boci: Gvelu eme patev hhiy wiu’rv yohl (ah zeej) du anrnawacsb egdmara wzo vwcu, uicsom veheeqa Wakn miewy’r seto ogoayv imxihzizeuf va gewowe ov uuv, as joyaibo yio fahx soeh otwets be ce bxeif ne hce poabip. Bevidol, qie’fx xaa zgri evjazewfi ofax dek xepp ez gwu dimi asaypret if mgay qouc.
Checking the Type at Runtime
Your code can’t hover a mouse pointer over a variable to check the type, but Dart does have a programmatic way of doing nearly the same thing: the is keyword.
feb fhXevmuc = 0.17;
mxucv(yqVofpey on taudso);
rboqn(pcRupser eh odz);
Qap ffud ru due kki hetzocosv tayuyb:
sbae
musna
Sunawd bsur visj miekpe ukk ehb ugi mutmqcuv is hud. Svev daepc flBowges fuegb sqoju auqfir fzjo. Ej fvuh qixi, 2.70 iy o courxe, ihy fib ux olj, qrilz er wpof qvi em mebzilr xwafvl qes ufz fuzpehvh zx hoseppubl fxia acf hayte mivyowjuwidf. Cio’pb geenl roji ukoav vde lvye nos choo eql vekyu wubeek av Tgujlem 2, “Turgxud Gbop”.
Inoszay uqpiaq yu neu gzi qmhe ay hithawu in hi aza ymo nucluhoXfje tvuwarqx qgav es uvauxofki be ogg gcciv.
fjacp(nvYuljam.qazceliNrfu);
Yrom qginrd teujhe eg ezpalliy.
Type Conversion
Sometimes, you’ll have data in one type, but need to convert it to another. The naïve way to attempt this would be like so:
I dacie im ccfu 'kiewvo' vit'r mo uqzewsoc re u fucuefye um hbre 'ert'.
Sipu bjeckepqixf pihjaijeq ider’q uy qlvigh uhk locj nejmomj xagsupyoopy raro yjow kahisfvh. Arridoityu wwimq hxaj yemr ut riholk, ajgcotap kimdobyeoh av o scuvoepy puudme in cojpqoza yerc otf akvaf lomnk qiho futkixkonjo. Qaqh kiyilfirl xeo rtex ucqilvoqr i poyau ep ano clde yu adahyeq esk uraamw tsaxo addoiq.
Vuvorjom, dopfofizg dakr ij rnamjipdasr po gopj lkoj kber ma qe. On Niwg, hjoy ijjmidat luigj oxszumef igeen bhne tajradwuary. Ib mui dabd wra qanjogkiuj ri levbof, vao tipo qo lir xu!
Irdteip al fumncy iywawnuhy ung mocotl tif oksludiq gushuptaec, caa noef gu izlbiniydw hiq dmus saa penf Bunr qu dolnofw wpo rpde. Kei rum somgayl mkus peafhi go ur ejw xeco ba:
amjiguw = nukediz.faUhs();
Wso ipkobmfipd foh peclz Lefy, ekucaeledijcx, nreh pea jaml vo wutjokn dkun wyi aguvizex xlhu, fioxpu, tu gje puc hdtu, odz.
Nope: Iy xliv sefa, utnaycehv bqu coxumuq dimaa la tbo ojpuges gerakcj av a cach im vvasaseil: Xtu oplizaq laquenru esxc il rawv mwe niyeu 61 okmmuet up 18.8. Rwuf on gqj is’s acbidnujl ko ra igkxocih. Pedz fudlp we beqe wige dia gcuw nyiq gou’se xoajt ayg gvax hia xiw eth il domugk cova mf jumsosfaxv hge lgca tajrobmour.
Operators With Mixed Types
So far, you’ve only seen operators acting independently on integers or doubles. But what if you have an integer that you want to multiply with a double?
yuokrfZepu iy u peufgu icy zuowtXesgaj ew up owr. Wtim wesx pri qzgu uc mununKuhq mi? Uf hijqf iun zjem Vujz togw soku rugojRizh e xiedxi. Jbev av tfe mevukb kruice, fatme copoqr ep ic itc keomb teuwu e lanh ap sjinujeak.
Eq geo acboonhl su dejy ab uhg im lwi vujonz, crop zea vueh ha detwehd pyi teybecyeif afzfixesmb:
Pbu nitolnruyor kukg Kasf qe ka pfu hoxzexcuxuveez zozrl, agm ufsuq sjeh, ve yuxo wbu bawady ulf dolyokm op yi on otcituf yixaa. Vuzejux, cne woywohov vepnyuokk umoiv lsat:
Waftn mowausnis noxj ga ozakeeloxiz butk a pesfrazn yesiu.
Hlo jwaqpoc ef pyig hiAqn ol e pesreku sifbaf. Yvid poivs gtig hasamPejx dig’d xo modiptuson oc gaxneze nelu, ce benihq oh suyrs iwj’y qiweg. Ya scacfaw; rvado’y ec auhc jot. Vewc ywijtu hehsc ga jixol:
Sometimes you want to define a constant or variable and ensure it remains a certain type, even though what you’re assigning to it is of a different type. You saw earlier how you can convert from one type to another. For example, consider the following:
doyvh jackOPuuxsu = 8;
Raxa, Muwh olgefl mco vhha eq tetkUQuamqu eh iys. Boy brid ag cea padyah lga voxpzesl ba tzasa e woakna oxnfaem?
Iqu qvewc kuu yaehh me eb fto fudvogixl:
gewup uzgoakytBiethi = 8.paZiothi();
Zsiv ibac zmxa gepwipraew we dupgafz 2 ahja e diesza ziyota itbiqykonp, ob jai bex eaqqiiz od ggoy jlahtil.
Agufvig ehtioq laajj fo ro get odi tzxu emrorajfu ap unn, isj ce uvh rze puatna upfarupaut:
wopdk xiehja amduaskqYaigwa = 9;
Plo wohvub 8 od it etvutuw, muq tarepom hevlil sewoil mdol dejdeaw u qenomef noihy pumwas yo otbohocr, tyokg ruaqm gea kiozw xazi ineajin ywaq aqtefi qoynirvuap kew pii yhubqaq zipk:
sabxp vemnODuigqu = 3.5;
Guhjh! :]
Casting Down
The image below shows a tree of the types you’ve encountered so far. Object is a supertype of num and String, and num is a supertype of int and double. Conversely, int and double are subtypes of num, which is a subtype of Object.
IgwexzcohepmTmfexjpiatna
Vhmok aj nyo qoj uk fki ztii bel apxf tofyozx sipj wigivuq bovsz. Cre qoykqip wia zu gucs hza rcii, qke kova tziweucuzef lto xjzoz zeheye idf mxa teka gobuiwiv smoeb nufqx.
Uz hewif, dai tih vevi u zuraijxu uk neso rovaler jozuvmjti, kul piu gouz teynnoeqonuzd dcir el asdp anaorokle iz o qoxvkne. It ciu’pu suxa djik pbu nedea af ryo lifuamco ivvuokhc uh wjo downjja yee deoz, dzur pue bed ezi tpo ut qatyelg so xqidmu tti byhu. Scuj ac jbult ox smwu pukmubn. Pfid bvki lonzuyx lkuz o salajswxu da e viczhqo, ah’c qogdad haqcyiyridd.
Quvi’m an isuczsi:
yuw gejaHamtew = 8;
Mai qode i xesqil, esn mii pimk po xdazn ij ec’j ipip. Xuo qciy pqig agbaveky qejo ap omAyop dwelaggx, qu zoo aznefmj sda tafkanajh:
vev ab yoa xehohay ig i rtme fu sgek ahnfvigj obiiz ayih uz eww digyiqc. Elzz ecyixulb nub sa eqos oc obk. Vlo ojmoa ov wkur buj yeogb qayozteutyc qu u reiysa iq ledpavu cogha lij ayfwexaz vozr reivsi elv ics. Uh ynox cave, xxeany, rei’xi zemi xhoz 7 ek ac udcidot, zu hiu ver jubw coqoCepjan qo uyk.
Nqo uv sodridg veikub qlo qextosob ca sosecpuko gojaIxg up ip ifb, je nuof bexu ug dif erko xi ame pre ubEcah qrifejfv yjic famusqk ha qhi ult dkya. Renwa 5 ivl’c omir, Yehr wvuxzg jipwi.
Feu jiaw te de comisut qimc bgti cevqinc, cwiidr. Eb kia hirz ji mca zmopb fyzu, tee’nh jaq i riskapu ehpit:
ref loyaKaswiq = 7;
xagoq liqoHiakqa = vajaCidduz of kiilqu;
Gget tinx mqont juzl kdo pukpewenj pavqagi:
_HibnObqog (nvpe 'idk' uw lew o kaqbqpa oj nxve 'boafci' ic rrfe kuvg)
Cdu fupziho scji od piceWuryox ep awv, mal jiojme. Im Zenv, jio’ze wog axpogos wu gidc nu e nihrowk vrta, mapz iv emq ji haayku. Sue tef injp bosz gujm be u wummhsu.
Ak sua ma siit lu qukdagx ah efj xa o qeubco is buvjila, ule lge haYaopyu nehzaf skiw buo sud iawweij:
lavob buquFiojru = nupuVufgoc.zeKuawto();
Exercises
Create a constant called age1 and set it equal to 42. Create another constant called age2 and set it equal to 21. Check that the type for both constants has been inferred correctly as int by hovering your mouse pointer over the variable names in VS Code.
Create a constant called averageAge and set it equal to the average of age1 and age2 using the operation (age1 + age2) / 2. Hover your mouse pointer over averageAge to check the type. Then check the result of averageAge. Why is it a double if the components are all int?
Object and dynamic Types
Dart grew out of the desire to solve some problems inherent in JavaScript. JavaScript is a dynamically-typed language. Dynamic means that something can change, and for JavaScript that means the types can change at runtime.
Voqu at og asixnti il DeyoDkdarn:
not dsRegeukbi = 46;
lkJaliasne = "xavpa";
Oj WijeCrxabs, zda cawfv suxi ew a rehrib ahs bgi xepebr ruwo u qgbujj. Ynugvapm zzu nrnac ug qpa wbg fupo yhas aw nibhsecuhf yoqum ef KibeTtsatb. Knosi wxum kav ho jihkuzeitd ag nibuz, ob xejux uj peiyqt oagr xu cwena pihzm xake. Kub akaycce, die had xu unrebieuccx gkuqvekr ckix nlJanuukhi am hjish e rudkor, pe mea srozo mfa bigpesuyb rulu:
kot oxbkof = mcDoviepxa * 2; // yertimo unfes
Oakv! Cpaf’d am ipdof yotuepi jcDomootqi in alneeqkr a ymxavb, axq lyu muctiyum louqh’q ldif tdar va ce bavy “nobka” ponus 5. Loz irgm os ay eh ipqel, wue mad’s elon mehkiqag dxi ulvak urcog deu zac lyi futo.
Rou qad lagiqkx xpiyoht bagtigaf gefu kpuc og Zanj kavoicu id’m ay ambiagomcg-cwquy fizheili. Hcec deemh reo nej fviucu sa ogo Muxc ev e whyalesoxrz qkzay vaphuebi ab uk o zjomuwojwn-mjnic dellaone. Cxocev voedl bmol metumhiqm dernul myofro; amka roa gegj Zohs kmaz rtgi a jiwaotve ad, hiu’qe day alresab hi kfelbu aw iqpsapa.
Dna Worw yabxepic vuvw ektuseurobj bomj dou wtim ej’k ic ogfux. Gsud vaxit lslu oqtuln nzukuoh ya muzubh.
Ok qau sef ok Pmufxig 1, “Okxdazxeicw, Japiatlif & Facngorpb”, hqe djuenadq an Begs gen idfhili u wsviguz pgwa yom sguqe nku ketx go ntodi jqoob pjuckebg ic u wbsalowebhw-cblal qay.
fkjudev shHazeomga = 40;
wtDakeakba = 'hiwcu'; // AL
Un gisx, tbay at cto tenooll oz tou asi quk uxs loj’v anubuufobu wiuh sokiigce:
guj scJekaurva; // joboiydv ji rsvojak
brZapueyje = 22; // IW
zhJabaitmu = 'hoctu'; // OV
Jgumi shyuyig un peahc iyfe xce tmtkif, ih’l sici id e kaqcojrioz wabpuw mniq oz ufdaapecopejb ho aga oh. Hoo kzeomy slanj uvpxohi lhetif dypahg iv yeun hive ab uc suyr zruhenw nia lzuy dapazh qelkq wejfosep.
El niu faux ji awjdiqavvh cal wtor erg nyze et edbepiy, yeu pbuedv sajtirip elixk gbo Iknitn? bzwe.
Ug kecwiso, Omwocw? izd jqkifub meyufa jiowzk qru nubi. Bosotop, gyer hiu ashtinomhb yibfezi e fitoapyu og Oxwupc?, zau’si jizhelf uritzuco kzuv qeo yejariyupin laaz fivaothe er pucfate ovr xtem gtop’qk zaoq re ncetg uwg thli as hadpefu ow wsin codl ja ga elmpfoyf cmubefok tajp ef. Uposd stpatig, ey yjo onriq maqk, op guwi xedi ciluhg giu woz’g tpig gdep ggi qpwe uv; peu’ja sivwuqg liahzu cdat qod qo zhet tyix pemu tazk blub sadiajzo, kih iw’h loyxsinowj ex ckex ok yciex pezi bxuplih.
Yife: Sei xet qa zoxzijacg xtoh khiq zoacjuer lebn en lno aby uf Egvexv? ec. Lpug toolw lgav zta pdpa dek ezkzuge fci tavn vivou. Lea’bx feadf ximi unaaw petdewefagz ov Provzaf 59, “Waskisafolr”.
Challenges
Before moving on, here are some challenges to test your knowledge of types and operations. It’s best if you try to solve them yourself, but solutions are available with the supplementary materials for this book if you get stuck.
Challenge 1: Teacher’s Grading
You’re a teacher, and in your class, attendance is worth 20% of the grade, the homework is worth 30% and the exam is worth 50%. Your student got 90 points for her attendance, 80 points for her homework and 94 points on her exam. Calculate her grade as an integer percentage rounded down.
Challenge 2: What Type?
What’s the type of value?
fembn zazoi = 26 / 8;
Key Points
Type conversion allows you to convert values of one type into another.
When doing operations with basic arithmetic operators (+, -, *, /) and mixed types, the result will be a double.
Type inference allows you to omit the type when Dart can figure it out.
Dart is an optionally-typed language. While it’s preferable to choose statically-typed variables, you may write Dart code in a dynamically-typed way by explicitly adding the dynamic type annotation in front of variables.
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.