Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish...

76
Introduction Fernando M. Q. Pereira [email protected]

Transcript of Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish...

Page 1: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Introduction

[email protected]

Page 2: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

IsitprofitabletodevelopApps?

-  Intheworld?-  InBrazil?-  Successstories?

Page 3: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

1.  Supercell:TheFinnishmobilegamepublisherisarounda$3billioncompany.MostfamousforitsgameClashofClans.

2.  King:TheCandyCrushlegendisstillgeneratingalotofmoney.Kinggeneratedmorethan$1.9billionin2013.

3.  GungHoOnline:Puzzle&Dragons,broughtin$650millionthroughApple'sAppStoreand$775millionthroughGooglePlayin2013.

Page 4: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Whatwerethemostdownloadedappsin2019?

Page 5: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash
Page 6: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

And,whataboutinBrazil?

Page 7: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

And,whataboutinBrazil?

Lista do Google dos melhores apps em 2018 tem 2 brasileiroshttps://noticias.uol.com.br/tecnologia/noticias/redacao/2018/12/03/baixou-lista-do-google-dos-melhores-apps-em-2018-tem-2-brasileiros-veja.htm HeltonSimõesGomes,12-03-2018

GuiaBolso Filmr

Page 8: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

https://tecnologia.uol.com.br/noticias/redacao/2018/11/08/dobra-n-de-apps-que-ganham-r-1-mi-no-brasil-qual-a-receita-do-sucesso.htm

Page 9: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

https://www.correiobraziliense.com.br/app/noticia/tecnologia/2015/05/11/interna_tecnologia,482694/brasil-decola-na-industria-de-apps-e-mercado-acumula-lucros-nesta-deca.shtml

Page 10: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

https://istoe.com.br/194216_OS+MILIONARIOS+DOS+APLICATIVOS/

Page 11: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Appsareimplementedinwhichprogramminglanguages?

Page 12: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Appsareimplementedinwhichprogramminglanguages?

-  Non-nativesupport-  C#-  Python-  JavaScript-  Php-  Lua-  ...

-  Nativesupport-  Java-  Dart-  C++[*]-  Kotlin

*:wecan'tdeveloptheentireappinC++

Page 13: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Whycan'twesimplystaywithJava?

-  WhenwasJavacreated?

-  WhatwouldyouliketochangeinJava?

Page 14: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Whycan'twesimplystaywithJava?

-  Verbosity-  NoREPL-  Poorsupporttofunctionalprogramming

Page 15: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Whycan'twesimplystaywithJava?

Verbosity

-  NoREPLPoorsupporttofunctionalprogramming

What'sthat?

Page 16: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Whycan'twesimplystaywithJava?

Verbosity

-  NoREPL- Canyounameeachprogramminglanguagebelow?

Poorsupporttofunctionalprogramming

>>>2+24>>>

- 2+2;valit=4:int-

?-Xis2+2.X=4.?-

#2+2;;;- :int=4#

Page 17: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Andwhat'sKotlin?

-  Whenwasitcreated?

-  Whocreatedit?-  Howdoesitlooklike?-  HowcanwerunKotlinprograms?-  Howcanweinstallit?

Page 18: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Installing(Linux)

SDKMan

$curl-shttps://get.sdkman.io|bash$sdkinstallkotlin

Snap

$sudosnapinstall--classickotlin

Page 19: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Installing(OSX)

Homebrew

$brewupdate$brewinstallkotlin

MacPorts

$sudoportinstallkotlin

Page 20: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Installing(IDE)

Page 21: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

HowcanwerunKotlinprograms?

Page 22: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

HowcanwerunKotlinprograms?

funmain(args:Array<String>){println("Hello,World!")}

$kotlinchello.kt-include-runtime-dhello.jar$java-jarhello.jar

Page 23: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

REPL

$kotlincWelcometoKotlinversion1.2.31(JRE1.8.0_65-b17)Type:helpforhelp,:quitforquit

>>>println("Hello,World!")Hello,World!

>>>2+24

Page 24: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Scripting

importjava.io.Filevalfolders=File(args[0]).listFiles{file->file.isDirectory()}folders?.forEach{folder->println(folder)}

$kotlinc-scriptlist_folders.kts..../FreqCounter../Scripts../Tests

list_folders.kts

Page 25: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Example:PointReader.kt

Implementaprogramthatreadsacsvfilecontainingalistof2Dpoints,andprintstheXcoordinateofeachpoint.

$cat~/Desktop/inst.csvX,Y2,3-1,4-2,-10,31,2

Example of input

-  Howmanyloopsdoyouneed?

-  Howmanylinesofcode?

Page 26: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Example:PointReader.kt

-  Wherearethetypes?

-  Wherearetheloops?-  Howtocompileandrunit?

importjava.io.Filefunmain(args:Array<String>){valfile=File(args[0])vallines=file.readLines().drop(1)valxList=lines.map{it.split(",").get(0).toFloat()}xList.forEach{println(it)}}

PointReader.kt

Page 27: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Example:PointReader.kt

importjava.io.Filefunmain(args:Array<String>){valfile=File(args[0])vallines=file.readLines().drop(1)valxList=lines.map{it.split(",").get(0).toFloat()}xList.forEach{println(it)}}

PointReader.kt

$kotlincPointReader.kt-include-runtime-dpointReader.jar$java-jarpointReader.jar~/Desktop/inst.csv2.0-1.0-2.00.01.0

Page 28: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Example:PointReader.kt

-  L4:what'sdrop(1)doing?Whydoweuseit?

-  L5:what'smap?-  L5:what's'it'init.split(",")?-  L5:what'ssplit(",")?

importjava.io.Filefunmain(args:Array<String>){valfile=File(args[0])vallines=file.readLines().drop(1)valxList=lines.map{it.split(",").get(0).toFloat()}xList.forEach{println(it)}}

PointReader.kt

1234567

Page 29: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

DEPARTMENTOFCOMPUTERSCIENCEUNIVERSIDADEFEDERALDEMINASGERAIS

FEDERALUNIVERSITYOFMINASGERAIS,BRAZIL

BASICSINTAX

Page 30: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Whatareprimitivetypes?

-  WhataretheprimitivetypesinC?

-  WhataboutJava?

Page 31: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

PrimitiveTypesinC

-  char-  short-  int-  long-  longlong-  float-  double-  longdouble

-  scalartypes- signed- unsigned-  int

signedlonglongx0=10;signedlonglongx1int=10;unsignedshort=10;unsignedshortint=10;

Page 32: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

PrimitiveTypesinJava

-  Integers- byte- chart- short-  int-  long

-  Floatingpoints- float- double

-  boolean

Page 33: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

PrimitiveTypesinKotlin

-  Integers- Byte- Short-  Int- Long

-  Floatingpoints- Float- Double

Page 34: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Canyouexplaineacherrorthatwegot?

>>>vali:Int=2>>>valb:Byte=8>>>valb:Byte=129error:...

>>>vald:Double=129.0>>>vald:Double=129error:...

>>>vald:Double=129.toDouble()

-  Integers- Byte- Short-  Int- Long

-  Floatingpoints- Float- Double

Page 35: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Typeconversionsmustbeexplicit

intn1=42;longn2=n1;

Java

Kotlin

>>>valn1:Int=42>>>valn2:long=n1error:...>>>valn2:Long=n1.toLong()

-  toByte()-  toShort()-  toInt()-  toLong()-  toFloat()-  toDouble()-  toChar()

Page 36: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Whymakingconversionsexplicit?

Kotlin

>>>valn1:Int=42>>>valn2:long=n1error:...>>>valn2:Long=n1.toLong()

-  Advantages?-  Disadvantages?-  Otherprogramminglanguages?

Page 37: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

InferencevsTypeAnnotations

importjava.io.Filefunmain(args:Array<String>){valpFile=File(args[0])vallines=pFile.readLines()valpOnly=lines.drop(1)valpList=pOnly.map{it.split(",")}valxStrs=pList.map{it.get(0)}valxList=xStrs.map{it.toFloat()}xList.forEach{println(it)}}

PointReader.kt

-  Canyouguesseachtype?

Page 38: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

InferencevsTypeAnnotations

importjava.io.Filefunmain(args:Array<String>){valpFile:File=File(args[0])vallines:List<String>=pFile.readLines()valpOnly:List<String>=lines.drop(1)valpList:List<List<String>>=pOnly.map{it.split(",")}valxStrs:List<String>=pList.map{it.get(0)}valxList:List<Float>=xStrs.map{it.toFloat()}xList.forEach{println(it)}}

PointReader.kt

-  What'stheadvantageofusingtypeinference?

-  What'stheadvantageofusingannotations?

Page 39: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

DEPARTMENTOFCOMPUTERSCIENCEUNIVERSIDADEFEDERALDEMINASGERAIS

FEDERALUNIVERSITYOFMINASGERAIS,BRAZIL

LISTSANDRANGES

Page 40: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

importjava.io.Filefunmain(args:Array<String>){valpFile:File=File(args[0])vallines:List<String>=pFile.readLines()valpOnly:List<String>=lines.drop(1)valpList:List<List<String>>=pOnly.map{it.split(",")}valxStrs:List<String>=pList.map{it.get(0)}valxList:List<Float>=xStrs.map{it.toFloat()}xList.forEach{println(it)}}

PointReader.kt

WhichoperationswouldyouexpecttofindinLists?

Page 41: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

BasicListOperations

>>>valitems=listOf(1,2,3,4)>>>items.first()1>>>items.last()4>>>items.drop(1)[2,3,4]>>>items.contains(2)true>>>items.get(2)3>>>items.indexOf(2)1>>>items.subList(1,3)[2,3]>>>items.dropLast(2)[1,2]

Page 42: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Rangesareasimplewaytobuildlistsanditerators

>>>valr=1..10>>>r1..10>>>r.first()1>>>r.last()10>>>r.toList()[1,2,3,4,5,6,7,8,9,10]>>>r.drop(1)[2,3,4,5,6,7,8,9,10]>>>r.contains(2)true>>>r.indexOf(3)2

Page 43: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

ListsandRangesgivesusControlStructures

>>>if(2in1..10){println("oi")}oi>>>for(iin1..4)println(i)1234>>>for(iinlistOf("a","b","cd","efg"))...println(i)abcdefg

Page 44: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

High-OrderFunction:map

-  Whatisx -> x * x ?

-  Andwhatisx -> x.toString() + "!" ?

>>>valitems=listOf(2,3,5,7,11,13)>>>items.map{x->x*x}[4,9,25,49,121,169]>>>items.map{x->x.toString()+"!"}[2!,3!,5!,7!,11!,13!]

Page 45: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

LambdaExpressions

>>>valf={a:Int,b:Int->a+b}>>>f(2,3)5

>>>valg={a:Float,b:Float,c:Float->a*b+c}>>>g(2.76F,3.14F,1.12F)9.7864

>>>valitems=listOf(2,3,5,7,11,13)>>>items.map{x->x*x}[4,9,25,49,121,169]

Page 46: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

AnonymousFunctions

>>>valh=fun(L:List<Int>,e:Int,d:Int):Int{...valaux=L.indexOf(e)...returnif(aux>-1)eelsed...}

>>>h(listOf(1,2,3),2,10)2

>>>h(listOf(1,2,3),4,10)10

-  What'sthedifferencebetweenusinganonymousfunctions(withthefunkeyword)andlambdablocks?

-  Couldyourewritethesamefunctionh,thistimeasalambdaexpression?

Page 47: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

LambdaExpressionsareAnonymousFunctions

>>>valh={L:List<Int>,e:Int,d:Int->if(L.indexOf(e)>-1)eelsed}

>>>h(listOf(1,2,3),2,10)2

>>>h(listOf(1,2,3),4,10)10

-  Whenisitmandatorytouseanonymousfunctions?

Page 48: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

What'sthetypeofeachLXandEX?

>>>valitems=listOf(2,3,5,7)

>>>valL0=items.map{x->kotlin.math.ln(x.toDouble())}>>>L0.javaClass???>>>valE0=L0.first()>>>E0.javaClass???

>>>valL1=items.map{x->x>4}>>>valE1=L1.first()>>>E1.javaClass???

>>>valL2=items.map{x->listOf(x)}>>>valE2=L2.first()>>>E2.first().javaClass???

Page 49: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

What'sthetypeofeachLXandEX?

>>>valitems=listOf(2,3,5,7)

>>>valL0=items.map{x->kotlin.math.ln(x.toDouble())}>>>L0.javaClassclassjava.util.ArrayList>>>valE0=L0.first()>>>E0.javaClassdouble

>>>valL1=items.map{x->x>4}>>>valE1=L1.first()>>>E1.javaClassboolean

>>>valL2=items.map{x->listOf(x)}>>>valE2=L2.first()>>>E2.first().javaClassclassjava.util.Collections$SingletonList

Page 50: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Thesingleparameterit

-  Whencanweuseit?

>>>items.map{kotlin.math.ln(it.toDouble())}[0.69,1.10,1.61,1.94]

>>>items.map{it>4}[false,false,true,true]

>>>items.map{listOf(it)}[[2],[3],[5],[7]]

Page 51: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

forvsforEach

-  What'sthecodeabovedoing?

>>>vallist=(1..1000).toList()

-  Andthisprogramabove,what'sitdoing?

>>>varx:Int=0>>>kotlin.system.measureNanoTime{for(iinlist){x+=i}}469793

-  Finally,whatistheforEachdoinginthecodeabove?-  Whichoneisfaster,forEachorfor,forlists?

>>>varx:Int=0>>>kotlin.system.measureNanoTime{list.forEach{x+=it}}397783

Page 52: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

InferencevsTypeAnnotations

importjava.io.Filefunmain(args:Array<String>){valpFile=File(args[0])vallines=pFile.readLines()valpOnly=lines.drop(1)valpList=pOnly.map{it.split(",")}valxStrs=pList.map{it.get(0)}valxList=xStrs.map{it.toFloat()}xList.forEach{println(it)}}

PointReader.kt

-  Canyouexplainnowwhatisdoingeachlineabove?

3456789

Page 53: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

High-OrderFunction:fold

-  Whatisfoldgoodfor?

>>>listOf(1,2,3).fold(0){acc,element->acc+element}6

>>>listOf("a","b","c").fold(""){acc,element->acc+element}abc

>>>listOf(true,false,true).fold(0){x,e->if(e)x+1elsex}2

Page 54: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Fillupthequestionmarks

>>>valL=listOf(2,3,5,7,11)>>>L.fold(0){x,e->if(e>x)eelsex}??

>>>(L.fold(0){x,e->x+e})/L.size??

Page 55: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Fillupthequestionmarks

-  What'sthisweirdsyntax:L.fold(0){x,e->x+e}?

>>>valL=listOf(2,3,5,7,11)>>>L.fold(0){x,e->if(e>x)eelsex}11

>>>(L.fold(0){x,e->x+e})/L.size5

Page 56: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

TheLastParameter

-  Ifthelastparameterisafunction,thenitcanbepassedoutsideparentheses.

>>>L.fold(0){x,e->x+e}28

>>>L.fold(0,{x,e->x+e})28

Page 57: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Usingreduce insteadoffold.

>>>L.reduce{x,e->if(e>x)eelsex}11

>>>L.reduce{x,e->if(e<x)eelsex}2

-  What'sthedifferencebetweenfold andreduce?

-  Whatwillhappenintheprogrambelow?

emptyList<Int>().reduce{x,e->if(e<x)eelsex}

Page 58: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Example:Centroid.kt

Implementaprogramthatreadsacsvfilecontainingalistof2Dpoints,andprintsthecentroidofthesepoints.

$cat~/Desktop/inst.csvX,Y3,30,4-1,-21,32,2

Example of input

-  What'sacentroid?

-  Whichoperationswillweneed?

Page 59: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Example:Centroid.kt

-  Whatisthemeaningof${xAvg}, ${yAvg}?-  Canyouthinkonwaysofimprovingthis

program?

importjava.io.Filefunmain(args:Array<String>){valfile=File(args[0])vallines=file.readLines()valpoints=lines.drop(1)valxL=points.map{it.split(",").get(0).toFloat()}valxAvg=xL.fold(.0){x,e->x+e}/xL.size.toFloat()valyL=points.map{it.split(",").get(1).toFloat()}valyAvg=yL.fold(.0){x,e->x+e}/yL.size.toFloat()print("Centroid=(${xAvg},${yAvg})")}

Centroid.kt

Page 60: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Externalfunction

-  Shouldwemovelines9and11towithinavg?

importjava.io.Filefunavg(list:List<Float>):Float{ returnlist.fold(.0F){x,e->x+e}/list.size.toFloat()}funmain(args:Array<String>){ valfile=File(args[0]) vallines=file.readLines() valpoints=lines.drop(1) valxList=points.map{it.split(",").get(0).toFloat()} valxAvg=avg(xList) valyList=points.map{it.split(",").get(1).toFloat()} valyAvg=avg(yList) print("Centroid=(${xAvg},${yAvg})")}

Centroid2.kt

123456789

10111213

Page 61: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Externalfunction

-  Whichfunctionismorereusable,avgoravg2?

importjava.io.Filefunavg2(list:List<String>,index:Int):Float{ valfList=list.map{it.split(",").get(index).toFloat()} returnfList.fold(.0F){x,e->x+e}/fList.size.toFloat()}funmain(args:Array<String>){ valfile=File(args[0]) vallines=file.readLines() valpoints=lines.drop(1) valxAvg=avg2(points,0) valyAvg=avg2(points,1) print("Centroid=(${xAvg},${yAvg})")}

Centroid3.kt

Page 62: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

TheSegregationPrinciple

-  Whichversionismorereusable?

Eachfunctionshouldhaveawell-definedobligation

funavg2(list:List<String>,index:Int):Float{valfList=list.map{it.split(",").get(index).toFloat()}valrVal=fList.fold(.0F){x,e->x+e}returnrVal/fList.size.toFloat()}

funavg1(list:List<Float>):Float{valrVal=list.fold(.0F){x,e->x+e}returnrVal/list.size.toFloat()}

Page 63: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

UsingtheKotlinLibrary

-  Whataretheadvantagesofusingthelibrary?Anddisadvantages?

-  Canweimprovethisprogramevenfurther?

importjava.io.Filefunmain(args:Array<String>){valfile=File(args[0])vallines=file.readLines()valpoints=lines.drop(1)valxList=points.map{it.split(",").get(0).toFloat()}valxAvg=xList.average()valyList=points.map{it.split(",").get(1).toFloat()}valyAvg=yList.average()print("Centroid=(${xAvg},${yAvg})")}

Centroid4.kt

Page 64: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Unstructureddata

-  Whatisthemeaningofthisline:it.split(",").get(1).toFloat()?

-  Howdoweknowthatget(1)willgivebacksomething?

-  Whatifthefilehasabadformat?

- Howmanythingscangowronginthiscase?

Page 65: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Unstructureddata

-  Whatisthemeaningofthisline:it.split(",").get(1).toFloat()?

-  Howdoweknowthatget(1)willgivebacksomething?

-  Whatifthefilehasabadformat?

- Howmanythingscangowronginthiscase?

$cat~/Desktop/inst.csvX,Y3,30

Example of bad input IndexOutOfBoundsException

Page 66: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Unstructureddata

-  Whatisthemeaningofthisline:it.split(",").get(1).toFloat()?

-  Howdoweknowthatget(1)willgivebacksomething?

-  Whatifthefilehasabadformat?

- Howmanythingscangowronginthiscase?

$cat~/Desktop/inst.csvX,Y3,30,frog

Another example of bad input NumberFormatException

Page 67: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Unstructureddata

-  Whatisthemeaningofthisline:it.split(",").get(1).toFloat()?

-  Howdoweknowthatget(1)willgivebacksomething?

-  Whatifthefilehasabadformat?

- Howmanythingscangowronginthiscase?

-  Howcanweimprovethisprogramtoeaseitsunderstanding?

Page 68: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

DEPARTMENTOFCOMPUTERSCIENCEUNIVERSIDADEFEDERALDEMINASGERAIS

FEDERALUNIVERSITYOFMINASGERAIS,BRAZIL

OBJECTSANDCLASSES

Page 69: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

ThePointClass

classPoint(valx:Float,valy:Float){ overridefuntoString():String{ return"(${x},${y})" }}

funline2Point(line:String):Point{ vallist=line.split(",") valx=list.get(0).toFloat() valy=list.get(1).toFloat() returnPoint(x,y)}

PointReader2.kt

-  Whereistheconstructor?

-  Howtoconvertafileintopoints?

Page 70: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Mappinglinesintopoints

funmain(args:Array<String>){valfile=File(args[0])vallines=file.readLines()vallDrop=lines.drop(1)valpoints=lDrop.map{line2Point(it)}points.forEach{println(it)}}

PointReader2.kt

$kotlincPointReader2.kt-include-runtime-dpointReader.jar$java-jarpointReader.jar~/Desktop/inst.csv(3.0,3.0)(0.0,4.0)(-1.0,-2.0)(1.0,3.0)(2.0,2.0)

Page 71: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

BackintoCentroids

-  CanyouusethenewclassPointtosolvetheproblemoffindingcentroids?

Page 72: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

BackintoCentroids

-  CanyouusethenewclassPointtosolvetheproblemoffindingcentroids?

funmain(args:Array<String>){valfile=File(args[0])vallines=file.readLines()vallDrop=lines.drop(1)valpoints=lDrop.map{line2Point(it)}valxAvg=points.map{it.x}.average()valyAvg=points.map{it.y}.average()print("Centroid=(${xAvg},${yAvg})\n")}

Page 73: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Example:RandomPairs.kt

Implementaprogramthatreadsatxtfilecontainingalistofstudents,andorganizesthestudentsintorandomteams.Thenumberofstudentsperteamisacommandlineargument.

$cats.txtARTURBRENOCAIOIVOJOÃOJOSEMATHEUSPEDROTHAISVINICIUS

Example of input

$java-jarrandomPairs.jars.txt3>[JOSE,ARTUR,CAIO]>[VINICIUS,JOÃO,MATHEUS]>[PEDRO,BRENO,THAIS]>[IVO]

$java-jarrandomPairs.jars.txt4>[PEDRO,CAIO,IVO,ARTUR]>[THAIS,MATHEUS,JOÃO,JOSE]>[BRENO,VINICIUS]

Example of outupt

Page 74: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Example:RandomPairs.kt

importjava.io.Filefunmain(args:Array<String>){valfile=File(args[0])valteamSize=args[1].toInt()vallines=file.readLines()valshuffled=lines.shuffled()valchunked=shuffled.chunked(teamSize)chunked.forEach{println(">$it")}}

RandomPairs.kt

-  Whatwouldhappenifwedonotinformenoughcommandlinearguments?

Page 75: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

$java-jarrandomPairs.jars.txtExceptioninthread"main"java.lang.ArrayIndexOutOfBoundsException:1atRandomPairsKt.main(RandomPairs.kt:5)

Missing argument

Checkinginputarguments

-  Modifytheprogram,sothatitreportsamissingargument,andasksuserstousetheexpectedsyntax.

Page 76: Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish mobile game publisher is around a $3 billion company. Most famous for its game Clash

Checkingthenumberofargumentsinthecommandline

importjava.io.Filefunmain(args:Array<String>){if(args.size<2){System.err.println("Syntax:cmd<file.txt><teamSize>")}else{valfile=File(args[0])valteamSize=args[1].toInt()vallines=file.readLines()valshuffled=lines.shuffled()valchunked=shuffled.chunked(teamSize)chunked.forEach{println(">$it")}}}

RandomPairs.kt

$java-jarrandomPairs.jars.txtSyntax:cmd<file.txt><teamSize>