Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish...
Transcript of Introductionevcomp.dcc.ufmg.br/wp-content/uploads/Kotlin-Intro.pdf · 1. Supercell: The Finnish...
Introduction
IsitprofitabletodevelopApps?
- Intheworld?- InBrazil?- Successstories?
1. Supercell:TheFinnishmobilegamepublisherisarounda$3billioncompany.MostfamousforitsgameClashofClans.
2. King:TheCandyCrushlegendisstillgeneratingalotofmoney.Kinggeneratedmorethan$1.9billionin2013.
3. GungHoOnline:Puzzle&Dragons,broughtin$650millionthroughApple'sAppStoreand$775millionthroughGooglePlayin2013.
Whatwerethemostdownloadedappsin2019?
And,whataboutinBrazil?
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
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
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
https://istoe.com.br/194216_OS+MILIONARIOS+DOS+APLICATIVOS/
Appsareimplementedinwhichprogramminglanguages?
Appsareimplementedinwhichprogramminglanguages?
- Non-nativesupport- C#- Python- JavaScript- Php- Lua- ...
- Nativesupport- Java- Dart- C++[*]- Kotlin
*:wecan'tdeveloptheentireappinC++
Whycan'twesimplystaywithJava?
- WhenwasJavacreated?
- WhatwouldyouliketochangeinJava?
Whycan'twesimplystaywithJava?
- Verbosity- NoREPL- Poorsupporttofunctionalprogramming
Whycan'twesimplystaywithJava?
Verbosity
- NoREPLPoorsupporttofunctionalprogramming
What'sthat?
Whycan'twesimplystaywithJava?
Verbosity
- NoREPL- Canyounameeachprogramminglanguagebelow?
Poorsupporttofunctionalprogramming
>>>2+24>>>
- 2+2;valit=4:int-
?-Xis2+2.X=4.?-
#2+2;;;- :int=4#
Andwhat'sKotlin?
- Whenwasitcreated?
- Whocreatedit?- Howdoesitlooklike?- HowcanwerunKotlinprograms?- Howcanweinstallit?
Installing(Linux)
SDKMan
$curl-shttps://get.sdkman.io|bash$sdkinstallkotlin
Snap
$sudosnapinstall--classickotlin
Installing(OSX)
Homebrew
$brewupdate$brewinstallkotlin
MacPorts
$sudoportinstallkotlin
Installing(IDE)
HowcanwerunKotlinprograms?
HowcanwerunKotlinprograms?
funmain(args:Array<String>){println("Hello,World!")}
$kotlinchello.kt-include-runtime-dhello.jar$java-jarhello.jar
REPL
$kotlincWelcometoKotlinversion1.2.31(JRE1.8.0_65-b17)Type:helpforhelp,:quitforquit
>>>println("Hello,World!")Hello,World!
>>>2+24
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
Example:PointReader.kt
Implementaprogramthatreadsacsvfilecontainingalistof2Dpoints,andprintstheXcoordinateofeachpoint.
$cat~/Desktop/inst.csvX,Y2,3-1,4-2,-10,31,2
Example of input
- Howmanyloopsdoyouneed?
- Howmanylinesofcode?
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
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
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
DEPARTMENTOFCOMPUTERSCIENCEUNIVERSIDADEFEDERALDEMINASGERAIS
FEDERALUNIVERSITYOFMINASGERAIS,BRAZIL
BASICSINTAX
Whatareprimitivetypes?
- WhataretheprimitivetypesinC?
- WhataboutJava?
PrimitiveTypesinC
- char- short- int- long- longlong- float- double- longdouble
- scalartypes- signed- unsigned- int
signedlonglongx0=10;signedlonglongx1int=10;unsignedshort=10;unsignedshortint=10;
PrimitiveTypesinJava
- Integers- byte- chart- short- int- long
- Floatingpoints- float- double
- boolean
PrimitiveTypesinKotlin
- Integers- Byte- Short- Int- Long
- Floatingpoints- Float- Double
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
Typeconversionsmustbeexplicit
intn1=42;longn2=n1;
Java
Kotlin
>>>valn1:Int=42>>>valn2:long=n1error:...>>>valn2:Long=n1.toLong()
- toByte()- toShort()- toInt()- toLong()- toFloat()- toDouble()- toChar()
Whymakingconversionsexplicit?
Kotlin
>>>valn1:Int=42>>>valn2:long=n1error:...>>>valn2:Long=n1.toLong()
- Advantages?- Disadvantages?- Otherprogramminglanguages?
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?
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?
DEPARTMENTOFCOMPUTERSCIENCEUNIVERSIDADEFEDERALDEMINASGERAIS
FEDERALUNIVERSITYOFMINASGERAIS,BRAZIL
LISTSANDRANGES
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?
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]
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
ListsandRangesgivesusControlStructures
>>>if(2in1..10){println("oi")}oi>>>for(iin1..4)println(i)1234>>>for(iinlistOf("a","b","cd","efg"))...println(i)abcdefg
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!]
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]
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?
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?
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???
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
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]]
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
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
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
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??
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
TheLastParameter
- Ifthelastparameterisafunction,thenitcanbepassedoutsideparentheses.
>>>L.fold(0){x,e->x+e}28
>>>L.fold(0,{x,e->x+e})28
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}
Example:Centroid.kt
Implementaprogramthatreadsacsvfilecontainingalistof2Dpoints,andprintsthecentroidofthesepoints.
$cat~/Desktop/inst.csvX,Y3,30,4-1,-21,32,2
Example of input
- What'sacentroid?
- Whichoperationswillweneed?
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
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
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
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()}
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
Unstructureddata
- Whatisthemeaningofthisline:it.split(",").get(1).toFloat()?
- Howdoweknowthatget(1)willgivebacksomething?
- Whatifthefilehasabadformat?
- Howmanythingscangowronginthiscase?
Unstructureddata
- Whatisthemeaningofthisline:it.split(",").get(1).toFloat()?
- Howdoweknowthatget(1)willgivebacksomething?
- Whatifthefilehasabadformat?
- Howmanythingscangowronginthiscase?
$cat~/Desktop/inst.csvX,Y3,30
Example of bad input IndexOutOfBoundsException
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
Unstructureddata
- Whatisthemeaningofthisline:it.split(",").get(1).toFloat()?
- Howdoweknowthatget(1)willgivebacksomething?
- Whatifthefilehasabadformat?
- Howmanythingscangowronginthiscase?
- Howcanweimprovethisprogramtoeaseitsunderstanding?
DEPARTMENTOFCOMPUTERSCIENCEUNIVERSIDADEFEDERALDEMINASGERAIS
FEDERALUNIVERSITYOFMINASGERAIS,BRAZIL
OBJECTSANDCLASSES
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?
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)
BackintoCentroids
- CanyouusethenewclassPointtosolvetheproblemoffindingcentroids?
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")}
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
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?
$java-jarrandomPairs.jars.txtExceptioninthread"main"java.lang.ArrayIndexOutOfBoundsException:1atRandomPairsKt.main(RandomPairs.kt:5)
Missing argument
Checkinginputarguments
- Modifytheprogram,sothatitreportsamissingargument,andasksuserstousetheexpectedsyntax.
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>