34
Kotlin for Android Developers (Preview) Learn Kotlin in an easy way while developing an Android App Antonio Leiva

Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

  • Upload
    others

  • View
    25

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

Kotlin for AndroidDevelopers (Preview)

Learn Kotlin in an easy way whiledeveloping an Android App

Antonio Leiva

Kotlin for Android Developers(Preview)Learn Kotlin in an easy way whiledeveloping an Android App

Antonio Leiva

copy2015 Antonio Leiva

Contents

I About this book 1

II Is this book for you 2

III About the author 3

1 Introduction 411 What is Kotlin 412 What do we get with Kotlin 6

2 Getting ready 1121 Android Studio 1122 Install Kotlin plugins 12

3 Creating a new project 1431 Create the project in Android Studio 1432 Configure Gradle 1533 Convert MainActivity to Kotlin code 1734 Test that everything works 17

4 Classes and functions 2041 How to declare a class 2042 Class inheritance 2143 Functions 2144 Constructor and functions parameters 22

5 Writing your first class 25

CONTENTS

51 Creating the layout 2552 The Recycler Adapter 27

Get the book 30

I About this bookIn this book Irsquoll be creating an Android app from ground up usingKotlin as the main language The idea is to learn the language byexample instead of following a typical reference book structureIrsquoll be stopping to explain the most interesting concepts and ideasabout Kotlin comparing it with Java 7 This way you can see whatthe differences are and which parts of the language will help youspeed up your work

This book is not meant to be a language reference but a tool forAndroid developers to learn Kotlin and be able to continue withtheir own projects by themselves Irsquoll be solving many of the typicalproblems we have to face in our daily lives by making use of thelanguage expressiveness and some other really interesting toolsand libraries However the text covers most Kotlin features so bythe end of the reading you will have a deep knowledge about thelanguage

The book is very practical so it is recommended to follow theexamples and the code in front of a computer and try everythingitrsquos suggested You could however take a first read to get a broadidea and then dive into practice

As you could read in previous pages (and probably the site were youdownloaded) this is a lean publication This means that the bookhas been progressing thanks to the readers comments Even thoughit is now finished I will review it from time to time to keep it up todate until the language is stable enough So feel free to write and tellme what you think about the book or what could be improved Inthe end it will also be your book I want this book to be the perfecttool for Android developers and as such all the help and ideas willbe welcomed

Thanks for becoming part of this exciting project

1

II Is this book for youThis book is written to be useful for Android developers who areinterested in learning Kotlin language

This book is for you if you are in some of the following situations

bull You have a basic knowledge about Android Development andthe Android SDK

bull You want to learn how to develop Android apps using Kotlinby following an example

bull You need a guide on how to solve many of the typical situ-ations an Android developer finds everyday using a cleanerand more expressive language

On the other hand this book may not be for you This is what youwonrsquot find in it

bull This is not a Kotlin Bible Irsquoll explain all the basics of thelanguage and even more complex ideas when they come outduring the process just whenwe need them So youwill learnby example and not the other way round

bull I will not explain how to develop an Android app You wonrsquotneed a deep knowledge of the platform but you will needsome basics such as some knowledge of Android StudioGradle Java programming and Android SDK You may evenlearn some new Android things in the process

bull This is not a guide to learn functional programming Ofcourse Irsquoll explain what you need as Java 7 is not functionalat all but I wonrsquot dive deep in functional topics

2

III About the authorAntonio Leiva is an Android Engineer who spends time learningabout new ways to get the most out of Android and then writesabout it He writes a blog at antonioleivacomsup1 about many differenttopics related to Android development

Antonio started as a consultant in CRM technologies but after sometime looking for his real passion he discovered the Android worldAfter getting some experience on such an awesome platform hestarted a new adventure at a mobile company where he led severalprojects for important Spanish companies

He nowworks as an Android Engineer at Plexsup2 where he also playsan important role in the design and UX of the Android applications

You can find Antonio on Twitter as lime_clsup3 or Google+ as+AntonioLeivaGordillo⁴

sup1httpantonioleivacomsup2httpplextvsup3httpstwittercomlime_cl⁴httpplusgooglecom+AntonioLeivaGordillolsquo

3

1 IntroductionYoursquove decided that Java 7 is obsolete and you deserve a moremodern language Nice choice As you may know even with Java8 out there which includes many of the improvements we wouldexpect from a modern language we Android developers are stillobliged to use Java 7 This is part because of legal issues Buteven without this limitation if new Android devices today startedshipping a virtual machine able to understand Java 8 we couldrsquotstart using it until current Android devices are so obsolete thatalmost nobody uses them So Irsquom afraid we wonrsquot see this momentsoon

But not everything is lost Thanks to the use of the Java VirtualMachine (JVM) we could write Android apps using any languagethat can be compiled to generate a bytecode the JVM is able tounderstand

As you can imagine there are a lot of options out there such asGroovy Scala Clojure and of course Kotlin In practice only someof them can be considered real alternatives

There are pros and cons on any of these languages and I suggestyou to take a look to some of them if you are not really sure whichlanguage you should use

11 What is Kotlin

Kotlin as described before is a JVM based language developed byJetBrains⁵ a company known for the creation of IntelliJ IDEA apowerful IDE for Java development Android Studio the officialAndroid IDE is based on IntelliJ as a platform plugin

⁵httpswwwjetbrainscom

4

1 Introduction 5

Kotlin was created with Java developers in mind and with IntelliJas its main development IDE And these are two very interestingcharacteristics for Android developers

bull Kotlin is very intuitive and easy to learn for Java devel-opers Most parts of the language are very similar to whatwe already know and the differences in basic concepts canbe learnt in no time

bull We have total integration with our daily IDE for freeAndroid Studio is perfectly capable to understand compileand run Kotlin code And the support for this language comesfrom the company who develops the IDE so we Androiddevelopers are first-class citizens

But this is only related to how the language integrates with ourtools What are the advantages of the language when compared toJava 7

bull Itrsquos more expressive this is one of its most importantqualities You can write more with much less code

bull Itrsquos safer Kotlin is null safe which means that we deal withpossible null situations in compile time to prevent executiontime exceptions We need to explicitly specify if an objectcan be null and then check its nullity before using it Youwill save a lot of time debugging null pointer exception andfixing nullity bugs

bull Itrsquos functional Kotlin is basically an object oriented lan-guage not a pure functional language However as manyother modern languages it uses many concepts from func-tional programming such as lambda expressions to resolvesome problems in a much easier way Another nice feature isthe way it deals with collections

bull It makes use of extension functions This means we canextend any class with new features even if we donrsquot haveaccess to the code of the class

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 2: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

Kotlin for Android Developers(Preview)Learn Kotlin in an easy way whiledeveloping an Android App

Antonio Leiva

copy2015 Antonio Leiva

Contents

I About this book 1

II Is this book for you 2

III About the author 3

1 Introduction 411 What is Kotlin 412 What do we get with Kotlin 6

2 Getting ready 1121 Android Studio 1122 Install Kotlin plugins 12

3 Creating a new project 1431 Create the project in Android Studio 1432 Configure Gradle 1533 Convert MainActivity to Kotlin code 1734 Test that everything works 17

4 Classes and functions 2041 How to declare a class 2042 Class inheritance 2143 Functions 2144 Constructor and functions parameters 22

5 Writing your first class 25

CONTENTS

51 Creating the layout 2552 The Recycler Adapter 27

Get the book 30

I About this bookIn this book Irsquoll be creating an Android app from ground up usingKotlin as the main language The idea is to learn the language byexample instead of following a typical reference book structureIrsquoll be stopping to explain the most interesting concepts and ideasabout Kotlin comparing it with Java 7 This way you can see whatthe differences are and which parts of the language will help youspeed up your work

This book is not meant to be a language reference but a tool forAndroid developers to learn Kotlin and be able to continue withtheir own projects by themselves Irsquoll be solving many of the typicalproblems we have to face in our daily lives by making use of thelanguage expressiveness and some other really interesting toolsand libraries However the text covers most Kotlin features so bythe end of the reading you will have a deep knowledge about thelanguage

The book is very practical so it is recommended to follow theexamples and the code in front of a computer and try everythingitrsquos suggested You could however take a first read to get a broadidea and then dive into practice

As you could read in previous pages (and probably the site were youdownloaded) this is a lean publication This means that the bookhas been progressing thanks to the readers comments Even thoughit is now finished I will review it from time to time to keep it up todate until the language is stable enough So feel free to write and tellme what you think about the book or what could be improved Inthe end it will also be your book I want this book to be the perfecttool for Android developers and as such all the help and ideas willbe welcomed

Thanks for becoming part of this exciting project

1

II Is this book for youThis book is written to be useful for Android developers who areinterested in learning Kotlin language

This book is for you if you are in some of the following situations

bull You have a basic knowledge about Android Development andthe Android SDK

bull You want to learn how to develop Android apps using Kotlinby following an example

bull You need a guide on how to solve many of the typical situ-ations an Android developer finds everyday using a cleanerand more expressive language

On the other hand this book may not be for you This is what youwonrsquot find in it

bull This is not a Kotlin Bible Irsquoll explain all the basics of thelanguage and even more complex ideas when they come outduring the process just whenwe need them So youwill learnby example and not the other way round

bull I will not explain how to develop an Android app You wonrsquotneed a deep knowledge of the platform but you will needsome basics such as some knowledge of Android StudioGradle Java programming and Android SDK You may evenlearn some new Android things in the process

bull This is not a guide to learn functional programming Ofcourse Irsquoll explain what you need as Java 7 is not functionalat all but I wonrsquot dive deep in functional topics

2

III About the authorAntonio Leiva is an Android Engineer who spends time learningabout new ways to get the most out of Android and then writesabout it He writes a blog at antonioleivacomsup1 about many differenttopics related to Android development

Antonio started as a consultant in CRM technologies but after sometime looking for his real passion he discovered the Android worldAfter getting some experience on such an awesome platform hestarted a new adventure at a mobile company where he led severalprojects for important Spanish companies

He nowworks as an Android Engineer at Plexsup2 where he also playsan important role in the design and UX of the Android applications

You can find Antonio on Twitter as lime_clsup3 or Google+ as+AntonioLeivaGordillo⁴

sup1httpantonioleivacomsup2httpplextvsup3httpstwittercomlime_cl⁴httpplusgooglecom+AntonioLeivaGordillolsquo

3

1 IntroductionYoursquove decided that Java 7 is obsolete and you deserve a moremodern language Nice choice As you may know even with Java8 out there which includes many of the improvements we wouldexpect from a modern language we Android developers are stillobliged to use Java 7 This is part because of legal issues Buteven without this limitation if new Android devices today startedshipping a virtual machine able to understand Java 8 we couldrsquotstart using it until current Android devices are so obsolete thatalmost nobody uses them So Irsquom afraid we wonrsquot see this momentsoon

But not everything is lost Thanks to the use of the Java VirtualMachine (JVM) we could write Android apps using any languagethat can be compiled to generate a bytecode the JVM is able tounderstand

As you can imagine there are a lot of options out there such asGroovy Scala Clojure and of course Kotlin In practice only someof them can be considered real alternatives

There are pros and cons on any of these languages and I suggestyou to take a look to some of them if you are not really sure whichlanguage you should use

11 What is Kotlin

Kotlin as described before is a JVM based language developed byJetBrains⁵ a company known for the creation of IntelliJ IDEA apowerful IDE for Java development Android Studio the officialAndroid IDE is based on IntelliJ as a platform plugin

⁵httpswwwjetbrainscom

4

1 Introduction 5

Kotlin was created with Java developers in mind and with IntelliJas its main development IDE And these are two very interestingcharacteristics for Android developers

bull Kotlin is very intuitive and easy to learn for Java devel-opers Most parts of the language are very similar to whatwe already know and the differences in basic concepts canbe learnt in no time

bull We have total integration with our daily IDE for freeAndroid Studio is perfectly capable to understand compileand run Kotlin code And the support for this language comesfrom the company who develops the IDE so we Androiddevelopers are first-class citizens

But this is only related to how the language integrates with ourtools What are the advantages of the language when compared toJava 7

bull Itrsquos more expressive this is one of its most importantqualities You can write more with much less code

bull Itrsquos safer Kotlin is null safe which means that we deal withpossible null situations in compile time to prevent executiontime exceptions We need to explicitly specify if an objectcan be null and then check its nullity before using it Youwill save a lot of time debugging null pointer exception andfixing nullity bugs

bull Itrsquos functional Kotlin is basically an object oriented lan-guage not a pure functional language However as manyother modern languages it uses many concepts from func-tional programming such as lambda expressions to resolvesome problems in a much easier way Another nice feature isthe way it deals with collections

bull It makes use of extension functions This means we canextend any class with new features even if we donrsquot haveaccess to the code of the class

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 3: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

Contents

I About this book 1

II Is this book for you 2

III About the author 3

1 Introduction 411 What is Kotlin 412 What do we get with Kotlin 6

2 Getting ready 1121 Android Studio 1122 Install Kotlin plugins 12

3 Creating a new project 1431 Create the project in Android Studio 1432 Configure Gradle 1533 Convert MainActivity to Kotlin code 1734 Test that everything works 17

4 Classes and functions 2041 How to declare a class 2042 Class inheritance 2143 Functions 2144 Constructor and functions parameters 22

5 Writing your first class 25

CONTENTS

51 Creating the layout 2552 The Recycler Adapter 27

Get the book 30

I About this bookIn this book Irsquoll be creating an Android app from ground up usingKotlin as the main language The idea is to learn the language byexample instead of following a typical reference book structureIrsquoll be stopping to explain the most interesting concepts and ideasabout Kotlin comparing it with Java 7 This way you can see whatthe differences are and which parts of the language will help youspeed up your work

This book is not meant to be a language reference but a tool forAndroid developers to learn Kotlin and be able to continue withtheir own projects by themselves Irsquoll be solving many of the typicalproblems we have to face in our daily lives by making use of thelanguage expressiveness and some other really interesting toolsand libraries However the text covers most Kotlin features so bythe end of the reading you will have a deep knowledge about thelanguage

The book is very practical so it is recommended to follow theexamples and the code in front of a computer and try everythingitrsquos suggested You could however take a first read to get a broadidea and then dive into practice

As you could read in previous pages (and probably the site were youdownloaded) this is a lean publication This means that the bookhas been progressing thanks to the readers comments Even thoughit is now finished I will review it from time to time to keep it up todate until the language is stable enough So feel free to write and tellme what you think about the book or what could be improved Inthe end it will also be your book I want this book to be the perfecttool for Android developers and as such all the help and ideas willbe welcomed

Thanks for becoming part of this exciting project

1

II Is this book for youThis book is written to be useful for Android developers who areinterested in learning Kotlin language

This book is for you if you are in some of the following situations

bull You have a basic knowledge about Android Development andthe Android SDK

bull You want to learn how to develop Android apps using Kotlinby following an example

bull You need a guide on how to solve many of the typical situ-ations an Android developer finds everyday using a cleanerand more expressive language

On the other hand this book may not be for you This is what youwonrsquot find in it

bull This is not a Kotlin Bible Irsquoll explain all the basics of thelanguage and even more complex ideas when they come outduring the process just whenwe need them So youwill learnby example and not the other way round

bull I will not explain how to develop an Android app You wonrsquotneed a deep knowledge of the platform but you will needsome basics such as some knowledge of Android StudioGradle Java programming and Android SDK You may evenlearn some new Android things in the process

bull This is not a guide to learn functional programming Ofcourse Irsquoll explain what you need as Java 7 is not functionalat all but I wonrsquot dive deep in functional topics

2

III About the authorAntonio Leiva is an Android Engineer who spends time learningabout new ways to get the most out of Android and then writesabout it He writes a blog at antonioleivacomsup1 about many differenttopics related to Android development

Antonio started as a consultant in CRM technologies but after sometime looking for his real passion he discovered the Android worldAfter getting some experience on such an awesome platform hestarted a new adventure at a mobile company where he led severalprojects for important Spanish companies

He nowworks as an Android Engineer at Plexsup2 where he also playsan important role in the design and UX of the Android applications

You can find Antonio on Twitter as lime_clsup3 or Google+ as+AntonioLeivaGordillo⁴

sup1httpantonioleivacomsup2httpplextvsup3httpstwittercomlime_cl⁴httpplusgooglecom+AntonioLeivaGordillolsquo

3

1 IntroductionYoursquove decided that Java 7 is obsolete and you deserve a moremodern language Nice choice As you may know even with Java8 out there which includes many of the improvements we wouldexpect from a modern language we Android developers are stillobliged to use Java 7 This is part because of legal issues Buteven without this limitation if new Android devices today startedshipping a virtual machine able to understand Java 8 we couldrsquotstart using it until current Android devices are so obsolete thatalmost nobody uses them So Irsquom afraid we wonrsquot see this momentsoon

But not everything is lost Thanks to the use of the Java VirtualMachine (JVM) we could write Android apps using any languagethat can be compiled to generate a bytecode the JVM is able tounderstand

As you can imagine there are a lot of options out there such asGroovy Scala Clojure and of course Kotlin In practice only someof them can be considered real alternatives

There are pros and cons on any of these languages and I suggestyou to take a look to some of them if you are not really sure whichlanguage you should use

11 What is Kotlin

Kotlin as described before is a JVM based language developed byJetBrains⁵ a company known for the creation of IntelliJ IDEA apowerful IDE for Java development Android Studio the officialAndroid IDE is based on IntelliJ as a platform plugin

⁵httpswwwjetbrainscom

4

1 Introduction 5

Kotlin was created with Java developers in mind and with IntelliJas its main development IDE And these are two very interestingcharacteristics for Android developers

bull Kotlin is very intuitive and easy to learn for Java devel-opers Most parts of the language are very similar to whatwe already know and the differences in basic concepts canbe learnt in no time

bull We have total integration with our daily IDE for freeAndroid Studio is perfectly capable to understand compileand run Kotlin code And the support for this language comesfrom the company who develops the IDE so we Androiddevelopers are first-class citizens

But this is only related to how the language integrates with ourtools What are the advantages of the language when compared toJava 7

bull Itrsquos more expressive this is one of its most importantqualities You can write more with much less code

bull Itrsquos safer Kotlin is null safe which means that we deal withpossible null situations in compile time to prevent executiontime exceptions We need to explicitly specify if an objectcan be null and then check its nullity before using it Youwill save a lot of time debugging null pointer exception andfixing nullity bugs

bull Itrsquos functional Kotlin is basically an object oriented lan-guage not a pure functional language However as manyother modern languages it uses many concepts from func-tional programming such as lambda expressions to resolvesome problems in a much easier way Another nice feature isthe way it deals with collections

bull It makes use of extension functions This means we canextend any class with new features even if we donrsquot haveaccess to the code of the class

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 4: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

CONTENTS

51 Creating the layout 2552 The Recycler Adapter 27

Get the book 30

I About this bookIn this book Irsquoll be creating an Android app from ground up usingKotlin as the main language The idea is to learn the language byexample instead of following a typical reference book structureIrsquoll be stopping to explain the most interesting concepts and ideasabout Kotlin comparing it with Java 7 This way you can see whatthe differences are and which parts of the language will help youspeed up your work

This book is not meant to be a language reference but a tool forAndroid developers to learn Kotlin and be able to continue withtheir own projects by themselves Irsquoll be solving many of the typicalproblems we have to face in our daily lives by making use of thelanguage expressiveness and some other really interesting toolsand libraries However the text covers most Kotlin features so bythe end of the reading you will have a deep knowledge about thelanguage

The book is very practical so it is recommended to follow theexamples and the code in front of a computer and try everythingitrsquos suggested You could however take a first read to get a broadidea and then dive into practice

As you could read in previous pages (and probably the site were youdownloaded) this is a lean publication This means that the bookhas been progressing thanks to the readers comments Even thoughit is now finished I will review it from time to time to keep it up todate until the language is stable enough So feel free to write and tellme what you think about the book or what could be improved Inthe end it will also be your book I want this book to be the perfecttool for Android developers and as such all the help and ideas willbe welcomed

Thanks for becoming part of this exciting project

1

II Is this book for youThis book is written to be useful for Android developers who areinterested in learning Kotlin language

This book is for you if you are in some of the following situations

bull You have a basic knowledge about Android Development andthe Android SDK

bull You want to learn how to develop Android apps using Kotlinby following an example

bull You need a guide on how to solve many of the typical situ-ations an Android developer finds everyday using a cleanerand more expressive language

On the other hand this book may not be for you This is what youwonrsquot find in it

bull This is not a Kotlin Bible Irsquoll explain all the basics of thelanguage and even more complex ideas when they come outduring the process just whenwe need them So youwill learnby example and not the other way round

bull I will not explain how to develop an Android app You wonrsquotneed a deep knowledge of the platform but you will needsome basics such as some knowledge of Android StudioGradle Java programming and Android SDK You may evenlearn some new Android things in the process

bull This is not a guide to learn functional programming Ofcourse Irsquoll explain what you need as Java 7 is not functionalat all but I wonrsquot dive deep in functional topics

2

III About the authorAntonio Leiva is an Android Engineer who spends time learningabout new ways to get the most out of Android and then writesabout it He writes a blog at antonioleivacomsup1 about many differenttopics related to Android development

Antonio started as a consultant in CRM technologies but after sometime looking for his real passion he discovered the Android worldAfter getting some experience on such an awesome platform hestarted a new adventure at a mobile company where he led severalprojects for important Spanish companies

He nowworks as an Android Engineer at Plexsup2 where he also playsan important role in the design and UX of the Android applications

You can find Antonio on Twitter as lime_clsup3 or Google+ as+AntonioLeivaGordillo⁴

sup1httpantonioleivacomsup2httpplextvsup3httpstwittercomlime_cl⁴httpplusgooglecom+AntonioLeivaGordillolsquo

3

1 IntroductionYoursquove decided that Java 7 is obsolete and you deserve a moremodern language Nice choice As you may know even with Java8 out there which includes many of the improvements we wouldexpect from a modern language we Android developers are stillobliged to use Java 7 This is part because of legal issues Buteven without this limitation if new Android devices today startedshipping a virtual machine able to understand Java 8 we couldrsquotstart using it until current Android devices are so obsolete thatalmost nobody uses them So Irsquom afraid we wonrsquot see this momentsoon

But not everything is lost Thanks to the use of the Java VirtualMachine (JVM) we could write Android apps using any languagethat can be compiled to generate a bytecode the JVM is able tounderstand

As you can imagine there are a lot of options out there such asGroovy Scala Clojure and of course Kotlin In practice only someof them can be considered real alternatives

There are pros and cons on any of these languages and I suggestyou to take a look to some of them if you are not really sure whichlanguage you should use

11 What is Kotlin

Kotlin as described before is a JVM based language developed byJetBrains⁵ a company known for the creation of IntelliJ IDEA apowerful IDE for Java development Android Studio the officialAndroid IDE is based on IntelliJ as a platform plugin

⁵httpswwwjetbrainscom

4

1 Introduction 5

Kotlin was created with Java developers in mind and with IntelliJas its main development IDE And these are two very interestingcharacteristics for Android developers

bull Kotlin is very intuitive and easy to learn for Java devel-opers Most parts of the language are very similar to whatwe already know and the differences in basic concepts canbe learnt in no time

bull We have total integration with our daily IDE for freeAndroid Studio is perfectly capable to understand compileand run Kotlin code And the support for this language comesfrom the company who develops the IDE so we Androiddevelopers are first-class citizens

But this is only related to how the language integrates with ourtools What are the advantages of the language when compared toJava 7

bull Itrsquos more expressive this is one of its most importantqualities You can write more with much less code

bull Itrsquos safer Kotlin is null safe which means that we deal withpossible null situations in compile time to prevent executiontime exceptions We need to explicitly specify if an objectcan be null and then check its nullity before using it Youwill save a lot of time debugging null pointer exception andfixing nullity bugs

bull Itrsquos functional Kotlin is basically an object oriented lan-guage not a pure functional language However as manyother modern languages it uses many concepts from func-tional programming such as lambda expressions to resolvesome problems in a much easier way Another nice feature isthe way it deals with collections

bull It makes use of extension functions This means we canextend any class with new features even if we donrsquot haveaccess to the code of the class

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 5: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

I About this bookIn this book Irsquoll be creating an Android app from ground up usingKotlin as the main language The idea is to learn the language byexample instead of following a typical reference book structureIrsquoll be stopping to explain the most interesting concepts and ideasabout Kotlin comparing it with Java 7 This way you can see whatthe differences are and which parts of the language will help youspeed up your work

This book is not meant to be a language reference but a tool forAndroid developers to learn Kotlin and be able to continue withtheir own projects by themselves Irsquoll be solving many of the typicalproblems we have to face in our daily lives by making use of thelanguage expressiveness and some other really interesting toolsand libraries However the text covers most Kotlin features so bythe end of the reading you will have a deep knowledge about thelanguage

The book is very practical so it is recommended to follow theexamples and the code in front of a computer and try everythingitrsquos suggested You could however take a first read to get a broadidea and then dive into practice

As you could read in previous pages (and probably the site were youdownloaded) this is a lean publication This means that the bookhas been progressing thanks to the readers comments Even thoughit is now finished I will review it from time to time to keep it up todate until the language is stable enough So feel free to write and tellme what you think about the book or what could be improved Inthe end it will also be your book I want this book to be the perfecttool for Android developers and as such all the help and ideas willbe welcomed

Thanks for becoming part of this exciting project

1

II Is this book for youThis book is written to be useful for Android developers who areinterested in learning Kotlin language

This book is for you if you are in some of the following situations

bull You have a basic knowledge about Android Development andthe Android SDK

bull You want to learn how to develop Android apps using Kotlinby following an example

bull You need a guide on how to solve many of the typical situ-ations an Android developer finds everyday using a cleanerand more expressive language

On the other hand this book may not be for you This is what youwonrsquot find in it

bull This is not a Kotlin Bible Irsquoll explain all the basics of thelanguage and even more complex ideas when they come outduring the process just whenwe need them So youwill learnby example and not the other way round

bull I will not explain how to develop an Android app You wonrsquotneed a deep knowledge of the platform but you will needsome basics such as some knowledge of Android StudioGradle Java programming and Android SDK You may evenlearn some new Android things in the process

bull This is not a guide to learn functional programming Ofcourse Irsquoll explain what you need as Java 7 is not functionalat all but I wonrsquot dive deep in functional topics

2

III About the authorAntonio Leiva is an Android Engineer who spends time learningabout new ways to get the most out of Android and then writesabout it He writes a blog at antonioleivacomsup1 about many differenttopics related to Android development

Antonio started as a consultant in CRM technologies but after sometime looking for his real passion he discovered the Android worldAfter getting some experience on such an awesome platform hestarted a new adventure at a mobile company where he led severalprojects for important Spanish companies

He nowworks as an Android Engineer at Plexsup2 where he also playsan important role in the design and UX of the Android applications

You can find Antonio on Twitter as lime_clsup3 or Google+ as+AntonioLeivaGordillo⁴

sup1httpantonioleivacomsup2httpplextvsup3httpstwittercomlime_cl⁴httpplusgooglecom+AntonioLeivaGordillolsquo

3

1 IntroductionYoursquove decided that Java 7 is obsolete and you deserve a moremodern language Nice choice As you may know even with Java8 out there which includes many of the improvements we wouldexpect from a modern language we Android developers are stillobliged to use Java 7 This is part because of legal issues Buteven without this limitation if new Android devices today startedshipping a virtual machine able to understand Java 8 we couldrsquotstart using it until current Android devices are so obsolete thatalmost nobody uses them So Irsquom afraid we wonrsquot see this momentsoon

But not everything is lost Thanks to the use of the Java VirtualMachine (JVM) we could write Android apps using any languagethat can be compiled to generate a bytecode the JVM is able tounderstand

As you can imagine there are a lot of options out there such asGroovy Scala Clojure and of course Kotlin In practice only someof them can be considered real alternatives

There are pros and cons on any of these languages and I suggestyou to take a look to some of them if you are not really sure whichlanguage you should use

11 What is Kotlin

Kotlin as described before is a JVM based language developed byJetBrains⁵ a company known for the creation of IntelliJ IDEA apowerful IDE for Java development Android Studio the officialAndroid IDE is based on IntelliJ as a platform plugin

⁵httpswwwjetbrainscom

4

1 Introduction 5

Kotlin was created with Java developers in mind and with IntelliJas its main development IDE And these are two very interestingcharacteristics for Android developers

bull Kotlin is very intuitive and easy to learn for Java devel-opers Most parts of the language are very similar to whatwe already know and the differences in basic concepts canbe learnt in no time

bull We have total integration with our daily IDE for freeAndroid Studio is perfectly capable to understand compileand run Kotlin code And the support for this language comesfrom the company who develops the IDE so we Androiddevelopers are first-class citizens

But this is only related to how the language integrates with ourtools What are the advantages of the language when compared toJava 7

bull Itrsquos more expressive this is one of its most importantqualities You can write more with much less code

bull Itrsquos safer Kotlin is null safe which means that we deal withpossible null situations in compile time to prevent executiontime exceptions We need to explicitly specify if an objectcan be null and then check its nullity before using it Youwill save a lot of time debugging null pointer exception andfixing nullity bugs

bull Itrsquos functional Kotlin is basically an object oriented lan-guage not a pure functional language However as manyother modern languages it uses many concepts from func-tional programming such as lambda expressions to resolvesome problems in a much easier way Another nice feature isthe way it deals with collections

bull It makes use of extension functions This means we canextend any class with new features even if we donrsquot haveaccess to the code of the class

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 6: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

II Is this book for youThis book is written to be useful for Android developers who areinterested in learning Kotlin language

This book is for you if you are in some of the following situations

bull You have a basic knowledge about Android Development andthe Android SDK

bull You want to learn how to develop Android apps using Kotlinby following an example

bull You need a guide on how to solve many of the typical situ-ations an Android developer finds everyday using a cleanerand more expressive language

On the other hand this book may not be for you This is what youwonrsquot find in it

bull This is not a Kotlin Bible Irsquoll explain all the basics of thelanguage and even more complex ideas when they come outduring the process just whenwe need them So youwill learnby example and not the other way round

bull I will not explain how to develop an Android app You wonrsquotneed a deep knowledge of the platform but you will needsome basics such as some knowledge of Android StudioGradle Java programming and Android SDK You may evenlearn some new Android things in the process

bull This is not a guide to learn functional programming Ofcourse Irsquoll explain what you need as Java 7 is not functionalat all but I wonrsquot dive deep in functional topics

2

III About the authorAntonio Leiva is an Android Engineer who spends time learningabout new ways to get the most out of Android and then writesabout it He writes a blog at antonioleivacomsup1 about many differenttopics related to Android development

Antonio started as a consultant in CRM technologies but after sometime looking for his real passion he discovered the Android worldAfter getting some experience on such an awesome platform hestarted a new adventure at a mobile company where he led severalprojects for important Spanish companies

He nowworks as an Android Engineer at Plexsup2 where he also playsan important role in the design and UX of the Android applications

You can find Antonio on Twitter as lime_clsup3 or Google+ as+AntonioLeivaGordillo⁴

sup1httpantonioleivacomsup2httpplextvsup3httpstwittercomlime_cl⁴httpplusgooglecom+AntonioLeivaGordillolsquo

3

1 IntroductionYoursquove decided that Java 7 is obsolete and you deserve a moremodern language Nice choice As you may know even with Java8 out there which includes many of the improvements we wouldexpect from a modern language we Android developers are stillobliged to use Java 7 This is part because of legal issues Buteven without this limitation if new Android devices today startedshipping a virtual machine able to understand Java 8 we couldrsquotstart using it until current Android devices are so obsolete thatalmost nobody uses them So Irsquom afraid we wonrsquot see this momentsoon

But not everything is lost Thanks to the use of the Java VirtualMachine (JVM) we could write Android apps using any languagethat can be compiled to generate a bytecode the JVM is able tounderstand

As you can imagine there are a lot of options out there such asGroovy Scala Clojure and of course Kotlin In practice only someof them can be considered real alternatives

There are pros and cons on any of these languages and I suggestyou to take a look to some of them if you are not really sure whichlanguage you should use

11 What is Kotlin

Kotlin as described before is a JVM based language developed byJetBrains⁵ a company known for the creation of IntelliJ IDEA apowerful IDE for Java development Android Studio the officialAndroid IDE is based on IntelliJ as a platform plugin

⁵httpswwwjetbrainscom

4

1 Introduction 5

Kotlin was created with Java developers in mind and with IntelliJas its main development IDE And these are two very interestingcharacteristics for Android developers

bull Kotlin is very intuitive and easy to learn for Java devel-opers Most parts of the language are very similar to whatwe already know and the differences in basic concepts canbe learnt in no time

bull We have total integration with our daily IDE for freeAndroid Studio is perfectly capable to understand compileand run Kotlin code And the support for this language comesfrom the company who develops the IDE so we Androiddevelopers are first-class citizens

But this is only related to how the language integrates with ourtools What are the advantages of the language when compared toJava 7

bull Itrsquos more expressive this is one of its most importantqualities You can write more with much less code

bull Itrsquos safer Kotlin is null safe which means that we deal withpossible null situations in compile time to prevent executiontime exceptions We need to explicitly specify if an objectcan be null and then check its nullity before using it Youwill save a lot of time debugging null pointer exception andfixing nullity bugs

bull Itrsquos functional Kotlin is basically an object oriented lan-guage not a pure functional language However as manyother modern languages it uses many concepts from func-tional programming such as lambda expressions to resolvesome problems in a much easier way Another nice feature isthe way it deals with collections

bull It makes use of extension functions This means we canextend any class with new features even if we donrsquot haveaccess to the code of the class

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 7: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

III About the authorAntonio Leiva is an Android Engineer who spends time learningabout new ways to get the most out of Android and then writesabout it He writes a blog at antonioleivacomsup1 about many differenttopics related to Android development

Antonio started as a consultant in CRM technologies but after sometime looking for his real passion he discovered the Android worldAfter getting some experience on such an awesome platform hestarted a new adventure at a mobile company where he led severalprojects for important Spanish companies

He nowworks as an Android Engineer at Plexsup2 where he also playsan important role in the design and UX of the Android applications

You can find Antonio on Twitter as lime_clsup3 or Google+ as+AntonioLeivaGordillo⁴

sup1httpantonioleivacomsup2httpplextvsup3httpstwittercomlime_cl⁴httpplusgooglecom+AntonioLeivaGordillolsquo

3

1 IntroductionYoursquove decided that Java 7 is obsolete and you deserve a moremodern language Nice choice As you may know even with Java8 out there which includes many of the improvements we wouldexpect from a modern language we Android developers are stillobliged to use Java 7 This is part because of legal issues Buteven without this limitation if new Android devices today startedshipping a virtual machine able to understand Java 8 we couldrsquotstart using it until current Android devices are so obsolete thatalmost nobody uses them So Irsquom afraid we wonrsquot see this momentsoon

But not everything is lost Thanks to the use of the Java VirtualMachine (JVM) we could write Android apps using any languagethat can be compiled to generate a bytecode the JVM is able tounderstand

As you can imagine there are a lot of options out there such asGroovy Scala Clojure and of course Kotlin In practice only someof them can be considered real alternatives

There are pros and cons on any of these languages and I suggestyou to take a look to some of them if you are not really sure whichlanguage you should use

11 What is Kotlin

Kotlin as described before is a JVM based language developed byJetBrains⁵ a company known for the creation of IntelliJ IDEA apowerful IDE for Java development Android Studio the officialAndroid IDE is based on IntelliJ as a platform plugin

⁵httpswwwjetbrainscom

4

1 Introduction 5

Kotlin was created with Java developers in mind and with IntelliJas its main development IDE And these are two very interestingcharacteristics for Android developers

bull Kotlin is very intuitive and easy to learn for Java devel-opers Most parts of the language are very similar to whatwe already know and the differences in basic concepts canbe learnt in no time

bull We have total integration with our daily IDE for freeAndroid Studio is perfectly capable to understand compileand run Kotlin code And the support for this language comesfrom the company who develops the IDE so we Androiddevelopers are first-class citizens

But this is only related to how the language integrates with ourtools What are the advantages of the language when compared toJava 7

bull Itrsquos more expressive this is one of its most importantqualities You can write more with much less code

bull Itrsquos safer Kotlin is null safe which means that we deal withpossible null situations in compile time to prevent executiontime exceptions We need to explicitly specify if an objectcan be null and then check its nullity before using it Youwill save a lot of time debugging null pointer exception andfixing nullity bugs

bull Itrsquos functional Kotlin is basically an object oriented lan-guage not a pure functional language However as manyother modern languages it uses many concepts from func-tional programming such as lambda expressions to resolvesome problems in a much easier way Another nice feature isthe way it deals with collections

bull It makes use of extension functions This means we canextend any class with new features even if we donrsquot haveaccess to the code of the class

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 8: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

1 IntroductionYoursquove decided that Java 7 is obsolete and you deserve a moremodern language Nice choice As you may know even with Java8 out there which includes many of the improvements we wouldexpect from a modern language we Android developers are stillobliged to use Java 7 This is part because of legal issues Buteven without this limitation if new Android devices today startedshipping a virtual machine able to understand Java 8 we couldrsquotstart using it until current Android devices are so obsolete thatalmost nobody uses them So Irsquom afraid we wonrsquot see this momentsoon

But not everything is lost Thanks to the use of the Java VirtualMachine (JVM) we could write Android apps using any languagethat can be compiled to generate a bytecode the JVM is able tounderstand

As you can imagine there are a lot of options out there such asGroovy Scala Clojure and of course Kotlin In practice only someof them can be considered real alternatives

There are pros and cons on any of these languages and I suggestyou to take a look to some of them if you are not really sure whichlanguage you should use

11 What is Kotlin

Kotlin as described before is a JVM based language developed byJetBrains⁵ a company known for the creation of IntelliJ IDEA apowerful IDE for Java development Android Studio the officialAndroid IDE is based on IntelliJ as a platform plugin

⁵httpswwwjetbrainscom

4

1 Introduction 5

Kotlin was created with Java developers in mind and with IntelliJas its main development IDE And these are two very interestingcharacteristics for Android developers

bull Kotlin is very intuitive and easy to learn for Java devel-opers Most parts of the language are very similar to whatwe already know and the differences in basic concepts canbe learnt in no time

bull We have total integration with our daily IDE for freeAndroid Studio is perfectly capable to understand compileand run Kotlin code And the support for this language comesfrom the company who develops the IDE so we Androiddevelopers are first-class citizens

But this is only related to how the language integrates with ourtools What are the advantages of the language when compared toJava 7

bull Itrsquos more expressive this is one of its most importantqualities You can write more with much less code

bull Itrsquos safer Kotlin is null safe which means that we deal withpossible null situations in compile time to prevent executiontime exceptions We need to explicitly specify if an objectcan be null and then check its nullity before using it Youwill save a lot of time debugging null pointer exception andfixing nullity bugs

bull Itrsquos functional Kotlin is basically an object oriented lan-guage not a pure functional language However as manyother modern languages it uses many concepts from func-tional programming such as lambda expressions to resolvesome problems in a much easier way Another nice feature isthe way it deals with collections

bull It makes use of extension functions This means we canextend any class with new features even if we donrsquot haveaccess to the code of the class

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 9: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

1 Introduction 5

Kotlin was created with Java developers in mind and with IntelliJas its main development IDE And these are two very interestingcharacteristics for Android developers

bull Kotlin is very intuitive and easy to learn for Java devel-opers Most parts of the language are very similar to whatwe already know and the differences in basic concepts canbe learnt in no time

bull We have total integration with our daily IDE for freeAndroid Studio is perfectly capable to understand compileand run Kotlin code And the support for this language comesfrom the company who develops the IDE so we Androiddevelopers are first-class citizens

But this is only related to how the language integrates with ourtools What are the advantages of the language when compared toJava 7

bull Itrsquos more expressive this is one of its most importantqualities You can write more with much less code

bull Itrsquos safer Kotlin is null safe which means that we deal withpossible null situations in compile time to prevent executiontime exceptions We need to explicitly specify if an objectcan be null and then check its nullity before using it Youwill save a lot of time debugging null pointer exception andfixing nullity bugs

bull Itrsquos functional Kotlin is basically an object oriented lan-guage not a pure functional language However as manyother modern languages it uses many concepts from func-tional programming such as lambda expressions to resolvesome problems in a much easier way Another nice feature isthe way it deals with collections

bull It makes use of extension functions This means we canextend any class with new features even if we donrsquot haveaccess to the code of the class

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 10: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

1 Introduction 6

bull Itrsquos highly interoperable You can continue using most li-braries and code written in Java because the interoperabilitybetween both languages is excellent Itrsquos even possible thatboth languages coexist in the same project

12 What do we get with Kotlin

Without diving too deep in Kotlin language (wersquoll learn about it innext chapters) these are some interesting features we miss in Java

Expresiveness

With Kotlin itrsquos much easier to avoid boilerplate because most typ-ical situations are covered by default in the language For instancein Java if we want to create a data class wersquoll need to write (or atleast generate) this code

1 public class Artist

2 private long id

3 private String name

4 private String url

5 private String mbid

6

7 public long getId()

8 return id

9

10

11 public void setId(long id)

12 thisid = id

13

14

15 public String getName()

16 return name

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 11: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

1 Introduction 7

17

18

19 public void setName(String name)

20 thisname = name

21

22

23 public String getUrl()

24 return url

25

26

27 public void setUrl(String url)

28 thisurl = url

29

30

31 public String getMbid()

32 return mbid

33

34

35 public void setMbid(String mbid)

36 thismbid = mbid

37

38

39 Override public String toString()

40 return Artist +

41 id= + id +

42 name= + name + +

43 url= + url + +

44 mbid= + mbid + +

45

46

47

With Kotlin you just need to make use of a data class

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 12: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

1 Introduction 8

1 data class Artist(

2 var id Long

3 var name String

4 var url String

5 var mbid String)

This data class auto-generates all the fields and property accessorsas well as some useful methods such as toString()

Null Safety

When we develop using Java most of our code is defensive Weneed to check continuously if something is null before using it ifwe donrsquot want to find unexpected NullPointerException Kotlin asmany other modern languages is null safe because we need toexplicitly specify if an object can be null by using the safe calloperator (written )

We can do things like this

1 This wont compile Artist cant be null

2 var notNullArtist Artist = null

3

4 Artist can be null

5 var artist Artist = null

6

7 Wont compile artist could be null and we need to d

8 eal with that

9 artistprint()

10

11 Will print only if artist = null

12 artistprint()

13

14 Smart cast We dont need to use safe call operator

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 13: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

1 Introduction 9

15 if we previously

16 checked nullity

17 if (artist = null)

18 artistprint()

19

20

21 Only use it when we are sure its not null Will thr

22 ow an exception otherwise

23 artistprint()

24

25 Use Elvis operator to give an alternative in case th

26 e object is null

27 val name = artistname empty

Extension functions

We can add new functions to any class Itrsquos a much more readablesubstitute to the typical utility classes we all have in our projectsWe could for instance add a new method to fragments to show atoast

1 fun Fragmenttoast(message CharSequence duration Int

2 = ToastLENGTH_SHORT)

3 ToastmakeText(getActivity() message duration)sh

4 ow()

5

We can now do

1 fragmenttoast(Hello world)

Functional support (Lambdas)

What if instead of having to write the creation of a new listenerevery time we need to declare what a click should do we could just

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 14: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

1 Introduction 10

define what we want to do We can indeed This (and many moreinteresting things) is what we get thanks to lambda usage

1 viewsetOnClickListener toast(Hello world)

This is only a small selection of what Kotlin can do to simplify yourcode Now that you know some of the many interesting features ofthe language you may decide this is not for you If you continuewersquoll start with the practice right away in the next chapter

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 15: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

2 Getting readyNow that you know some little examples of what you may do withKotlin Irsquom sure you want to start to put it into practice as soon aspossible Donrsquot worry these first chapters will help you configureyour development environment so that you can start writing somecode immediately

21 Android Studio

First thing you need is to have Android Studio installed As youmay know Android Studio is the official Android IDE which waspublicly presented in 2013 as a preview and finally released in 2014

Android Studio is implemented as a plugin over IntelliJ IDEA⁶ aJava IDE created by Jetbrains⁷ the company which is also behindKotlin So as you can see everything is tightly connected

The adoption of Android Studio was an important change forAndroid developers First because we left behind the buggy Eclipseand moved to a software specifically designed for Java developerswhich gives us a perfect interaction with the language We enjoyawesome features such as a fast and impressively smart codecompletion or really powerful analyzing and refactor tools amongothers

And second Gradle⁸ became the official build system for Androidwhich meant a whole bunch of new possibilities related to versionbuilding and deploy Two of the most interesting functions are buildsystems and flavours which let you create infinite versions of the

⁶httpswwwjetbrainscomidea⁷httpswwwjetbrainscom⁸httpsgradleorg

11

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 16: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

2 Getting ready 12

app (or even different apps) really easily while using the same codebase

If you are still using Eclipse Irsquom afraid you need to switch toAndroid Studio if you want to practice many of the parts includedin this book The Kotlin team is creating a plugin for Eclipse but itwill be always far behind from the one in Android Studio and theintegration wonrsquot be so perfect You will also discover what you aremissing really soon as you start using it

Irsquom not covering the use of Android Studio or Gradle because this isnot the focus of the book but if you havenrsquot used these tools beforedonrsquot panic Irsquom sure yoursquoll be able to follow the book and learn thebasics in the meanwhile

Download Android Studio from the official page⁹ if you donrsquot haveit already

22 Install Kotlin plugins

The IDE by itself is not able to understand Kotlin As I mentionedin the previous section it was designed to work with Java But theKotlin team has created a powerful set of plugins which will makeour lives easier Go to the plugins section inside Android StudioPreferences and install these two plugins

bull Kotlin This is the basic plugin It will let you use AndroidStudio to write and interact with Kotlin code Itrsquos updatedevery time a new version of the language is released so thatwe canmake use of the new features and find alternatives andwarnings of deprecations This is the only plugin you need towrite Android apps using Kotlin But wersquoll be using anotherone

⁹httpsdeveloperandroidcomsdkindexhtml

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 17: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

2 Getting ready 13

bull Kotlin Android Extensions the Kotlin team has also re-leased another interesting plugin for Android developersThese Android Extensions will let you automatically injectall the views in an XML into an activity for instance withoutthe need of using findViewById() You will get an propertycasted into the proper view type right away You will needto install this plugin to use this interesting feature Wersquoll talkdeeper about it in next chapters

Now our environment is ready to understand the language compileit and execute it just as seamlessly as if we were using Java

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 18: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

3 Creating a new projectIf you are already used to Android Studio and Gradle this chapterwill be quite easy I donrsquot want to give many details nor screensbecause UI changes from time to time and these lines wonrsquot beuseful anymore

Our app is consisting on a simple weather app such as the oneused in Googlersquos Beginners Course in Udacitysup1⁰ Wersquoll be probablypaying attention to different things but the idea of the app will bethe same because it includes many of the things you will find in atypical app If your Android level is low I recommend this courseitrsquos really easy to follow

31 Create the project in Android Studio

First of all open Android Studio and choose Create new Project Itwill ask for a name you can call it whatever you want WeatherAppfor instance Then you need to set a Company Domain As you arenot releasing the app this field is not very important either but ifyou have your own domain you can use that one Also choose alocation for the project wherever you want to save it

In next step yoursquoll be asked about the minimum API version Wersquollselect API 15 because one of the libraries wersquoll be using needs API15 as minimum Yoursquoll be targeting most Android users anywayDonrsquot choose any other platform rather than Phone and Tablet fornow

Finally we are required to choose an activity template to start withWe can choose Add no Activity and start from scratch (that would

sup1⁰httpswwwudacitycomcourseandroid-development-for-beginners--ud837

14

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 19: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

3 Creating a new project 15

be the best idea when starting a Kotlin project) but wersquoll ratherchoose Empty Activity because Irsquoll show you later an interestingfeature in the Kotlin plugin

Donrsquot worrymuch about the name of the activities layouts etc thatyou will find in next screen Wersquoll change them later if we need toPress Finish and let Android Studio do its work

32 Configure Gradle

The Kotlin plugin includes a tool which does the Gradle configura-tion for us But I prefer to keep control of what Irsquom writing in myGradle files otherwise they can get messy rather easily Anywayitrsquos a good idea to know how thingswork before using the automatictools so wersquoll be doing it manually this time

First you need to modify the parent buildgradle so that it lookslike this

1 buildscript

2 extsupport_version = 2311

3 extkotlin_version = 100-beta-2423

4 extanko_version = 073

5 repositories

6 jcenter()

7

8 dependencies

9 classpath comandroidtoolsbuildgradle131

10 classpath orgjetbrainskotlinkotlin-gradle-p

11 lugin$kotlin_version

12

13

14

15 allprojects

16 repositories

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 20: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

3 Creating a new project 16

17 jcenter()

18

19

As you can see we are creating a variable which saves currentKotlin version Check which version is available when yoursquorereading these lines because therersquos probably a new version Weneed that version number in several places for instance in the newdependency you need to add for the Kotlin plugin Yoursquoll need itagain in the module buildgradle where wersquoll specify that thismodule uses the Kotlin plugin

Wersquoll do the same for the support library as well as Anko libraryThis way itrsquos easier to modify all the versions in a row as well asadding new libraries that use the same version without having tochange the version everywhere

Wersquoll add the dependencies to Kotlin standard library Ankolibrary and the Kotlin Android Extensions plugin

1 apply plugin comandroidapplication

2 apply plugin kotlin-android

3

4 android

5

6

7

8 dependencies

9 compile comandroidsupportappcompat-v7$support_

10 version

11 compile orgjetbrainskotlinkotlin-stdlib$kotlin

12 _version

13 compile orgjetbrainsankoanko-sdk15$anko_versio

14 n

15 compile orgjetbrainsankoanko-support-v4$anko_v

16 ersion

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 21: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

3 Creating a new project 17

17

18

19 buildscript

20 repositories

21 jcenter()

22

23 dependencies

24 classpath orgjetbrainskotlinkotlin-android-ex

25 tensions$kotlin_version

26

27

Anko library needs a couple of dependencies The first one refers tothe minimum supported SDK Itrsquos important not to be higher thanthe minimum SDK defined in your buildgradle sdk19 sdk21 andsdk23 are also available The second one adds extra features to thesupport-v4 library which we are implicitly using when importingappcompat-v7

33 Convert MainActivity to Kotlin code

An interesting feature the Kotlin plugin includes is the ability toconvert from Java to Kotlin code As any automated process itwonrsquot be perfectly optimised but it will help a lot in your first daysuntil you start getting used to Kotlin language

So we are using it in our MainActivityjava class Open the fileand select Code -gt Convert Java File to Kotlin File

34 Test that everything works

Wersquore going to add some code to test Kotlin Android Extensionsare working Irsquom not explaining much about it yet but I want to be

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 22: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

3 Creating a new project 18

sure this is working for you Itrsquos probably the trickiest part in thisconfiguration

First go to activity_mainxml and set an id for the TextView

1 ltTextView

2 androidid=+idmessage

3 androidtext=stringhello_world

4 androidlayout_width=wrap_content

5 androidlayout_height=wrap_contentgt

Now add the synthetic import to the activity (donrsquot worry if youdonrsquot understand much about it yet)

1 import kotlinxandroidsyntheticactivity_main

At onCreate you can now get access to that TextView directly

1 override fun onCreate(savedInstanceState Bundle)

2 superonCreate(savedInstanceState)

3 setContentView(Rlayoutactivity_main)

4 messagetext = Hello Kotlin

5

Thanks to Kotlin interoperability with Java we can use settersand getters methods from Java libraries as a property in KotlinWersquoll talk about properties later but just notice that we can usemessagetext instead of messagesetText for free The compilerwill use the real Java methods so therersquos no performance overheadwhen using it

Now run the app and see everything itrsquos working fine Check thatthe message TextView is showing the new content If you haveany doubts or want to review some code take a look at Kotlin for

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 23: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

3 Creating a new project 19

Android Developers repositorysup1sup1 Irsquoll be adding a new commit forevery chapter when the chapter implies changes in code so be sureto review it to check all the changes

Next chapters will cover some of the new things you are seeingin the converted MainActivity Once you understand the slightdifferences between Java and Kotlin yoursquoll be able to create newcode by yourself much easier

sup1sup1httpsgithubcomantoniolgKotlin-for-Android-Developers

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 24: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

4 Classes and functionsClasses in Kotlin follow a really simple structure However thereare some slight differences from Java that you will want to knowbefore we continue You can use trykotlinlangorgsup1sup2 to test this andsome other simple examples without the need of a real project anddeploy to a device

41 How to declare a class

If you want to declare a class you just need to use the keywordclass

1 class MainActivity

2

3

Classes have a unique default constructor Wersquoll see in futurelessons that we can create extra constructors for some edge casesbut keep in mind that most situations only require a single con-structor Parameters are written just after the name Brackets arenot needed in a class if it doesnrsquot have any content

1 class Person(name String surname String)

Wherersquos the body of the constructor then You can declare an init

block

sup1sup2httptrykotlinlangorg

20

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 25: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

4 Classes and functions 21

1 class Person(name String surname String)

2 init

3

4

5

42 Class inheritance

By default a class always extends from Any (similar to Java Object)but we can extend any other classes Classes are closed by default(final) so we can only extend a class if itrsquos explicitly declared asopen or abstract

1 open class Animal(name String)

2 class Person(name String surname String) Animal(na

3 me)

Note that when using the single constructor nomenclature we needto specify the parameters wersquore using for the parent constructorThatrsquos the substitution to super() call in Java

43 Functions

Functions (our methods in Java) are declared just using the fun

keyword

1 fun onCreate(savedInstanceState Bundle)

2

It you donrsquot specify a return value it will return Unit similar tovoid in Java though this is really an object You can of coursespecify any type for the return value

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 26: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

4 Classes and functions 22

1 fun add(x Int y Int) Int

2 return x + y

3

Tip Semi-colons are not necessaryAs you can see in the previous example Irsquom not usingsemi-colons at the end of the sentences While youcan use them semi-colons are not necessary and itrsquosa good practice not to use them When you get usedyoursquoll find that it saves you a lot of time

However if the result can be calculated using a single expressionyou can get rid of brackets and use equal

1 fun add(x Int y Int) Int = x + y

44 Constructor and functionsparameters

Parameters in Kotlin are a bit different from Java As you can seewe first write the name of the parameter and then its type

1 fun add(x Int y Int) Int

2 return x + y

3

An extremely useful thing about parameters is that we can makethem optional by specifying a default value Here it is an exampleof a function you could create in an activity which uses a toast toshow a message

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 27: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

4 Classes and functions 23

1 fun toast(message String length Int = ToastLENGTH_S

2 HORT)

3 ToastmakeText(this message length)show()

4

As you can see the second parameter (length) specifies a defaultvalue This means you can write the second value or not whichavoids the need of function overloading

1 toast(Hello)

2 toast(Hello ToastLENGTH_LONG)

This would be equivalent to the next code in Java

1 void toast(String message)

2 toast(message ToastLENGTH_SHORT)

3

4

5 void toast(String message int length)

6 ToastmakeText(this message length)show()

7

And this can be as complex as you want Check this other example

1 fun niceToast(message String

2 tag String = MainActivityclassjavasi

3 mpleName

4 length Int = ToastLENGTH_SHORT)

5 ToastmakeText(this [$tag] $message length)sho

6 w()

7

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 28: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

4 Classes and functions 24

Irsquove added a third parameter that includes a tag which defaults tothe class name The amount of overloads wersquod need in Java growsexponentially You can now make these calls

1 toast(Hello)

2 toast(Hello MyTag)

3 toast(Hello MyTag ToastLENGTH_SHORT)

And there is even another option because you can use namedarguments which means you can write the name of the argumentpreceding the value to specify which one you want

1 toast(message = Hello length = ToastLENGTH_SHORT)

Tip String templatesYou can use template expressions directly in yourstrings This will help you write complex stringsbased on fixed and variable parts in a really simpleway In the previous example I used [$className]

$message

As you can see anytime you want to add an expres-sion you need to use the $ symbol If the expressionis a bit more complex yoursquoll need to add a couple ofbrackets Your name is $username

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 29: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

5 Writing your first classWe already have our MainActivitykt class This activity willrender a list of daily forecast for the next week so the layoutrequires some changes

51 Creating the layout

The main control that will support the forecast list will be a Recy-

clerView so you need to add a new dependency to the buildgradle

1 dependencies

2 compile fileTree(dir libs include [jar])

3 compile comandroidsupportappcompat-v7$support_

4 version

5 compile comandroidsupportrecyclerview-v7$suppo

6 rt_version

7

8

Now in activity_mainxml

25

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 30: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

5 Writing your first class 26

1 ltFrameLayout xmlnsandroid=httpschemasandroidcom

2 apkresandroid

3 androidlayout_width=match_parent

4 androidlayout_height=match_parentgt

5

6 ltandroidsupportv7widgetRecyclerView

7 androidid=+idforecast_list

8 androidlayout_width=match_parent

9 androidlayout_height=match_parentgt

10

11 ltFrameLayoutgt

In MainActivitykt remove the line we added to test everythingworked (it will be showing an error now) For the moment wersquollcontinue using the good old findViewById()

1 val forecastList = findViewById(Ridforecast_list) as

2 RecyclerView

3 forecastListlayoutManager = LinearLayoutManager(this)

As you can see we define the variable and cast it to RecyclerViewItrsquos a bit different from Java and wersquoll see those differences in thenext chapter A LayoutManager is also specified using the propertynaming instead of the setter A list will be enough for this layout

Object instantiationObject instantiation presents some differences fromJava too As you can see we omit the ldquonewrdquo word Theconstructor call is still there but we save four pre-cious characters LinearLayoutManager(this) cre-ates an instance of the object

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 31: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

5 Writing your first class 27

52 The Recycler Adapter

We need an adapter for the recycler too I talked about Recy-

clerView in my blogsup1sup3 some time ago so it may help you if yourare not used to it

The views used in the RecyclerViewwill be just TextViews for nowand a simple list of texts that wersquoll create manually Add a newKotlin file called ForecastListAdapterkt and include this code

1 public class ForecastListAdapter(val items ListltString

2 gt)

3 RecyclerViewAdapterltForecastListAdapterViewHo

4 ldergt()

5

6 override fun onCreateViewHolder(parent ViewGroup

7 viewType Int)

8 ForecastListAdapterViewHolder

9 return ViewHolder(TextView(parentcontext))

10

11

12 override fun onBindViewHolder(holder ForecastListA

13 dapterViewHolder

14 position Int)

15 holdertextViewtext = itemsget(position)

16

17

18 override fun getItemCount() Int = itemssize()

19

20 class ViewHolder(val textView TextView) Recycler

21 ViewViewHolder(textView)

22

Again we can access to the context and the text as properties You

sup1sup3httpantonioleivacomrecyclerview

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 32: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

5 Writing your first class 28

can keep doing it as usual (using getters and setter) but yoursquoll get awarning from the compiler This check can be disabled if you preferto keep using the Java way Once you get used to properties you willlove it anyway and it saves some amount of extra characters

Back to the MainActivity now just create the list of strings andthen assign the adapter

1 private val items = listOf(

2 Mon 623 - Sunny - 3117

3 Tue 624 - Foggy - 218

4 Wed 625 - Cloudy - 2217

5 Thurs 626 - Rainy - 1811

6 Fri 627 - Foggy - 2110

7 Sat 628 - TRAPPED IN WEATHERSTATION - 2318

8 Sun 629 - Sunny - 207

9 )

10

11 override fun onCreate(savedInstanceState Bundle)

12

13 val forecastList = findViewById(Ridforecast_list)

14 as RecyclerView

15 forecastListlayoutManager = LinearLayoutManager(th

16 is)

17 forecastListadapter = ForecastListAdapter(items)

18

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 33: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

5 Writing your first class 29

List creationThough Irsquoll talk about collections later on this bookI just want to explain for now that you can createconstant lists (what we will see as immutable soon)by using the helper function listOf It receives avararg of items of any type and infers the type ofthe result

There are many other alternative functions such assetOf arrayListOf or hashSetOf among others

I also moved some classes to new packages in order to improveorganisation

We saw many new things in such a small amount of code so Irsquollbe covering it in the next chapter We canrsquot continue until welearn some important concepts about basic types variables andproperties

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book
Page 34: Kotlin for Android Developers (Preview) - Antonio Leivaantonioleiva.com/.../2015/08/kotlin-for-android-developers-preview.pdf · Gradle, Java programming and Android SDK. You may

Get the bookHope you enjoyed this preview of Kotlin for Android DevelopersAs a thank you for being part of the newsletter and reading up tothis point Irsquom giving you a 15 discountsup1⁴ on it so that you cankeep learning about it

Thanks for becoming part of this Please contact if you needsomething I can help with at contactantonioleivacomsup1⁵

Best

Antonio Leiva

sup1⁴httpgoogltaoYJhsup1⁵mailtocontactantonioleivacom

30

  • Table of Contents
  • I About this book
  • II Is this book for you
  • III About the author
  • 1 Introduction
    • 11 What is Kotlin
    • 12 What do we get with Kotlin
      • 2 Getting ready
        • 21 Android Studio
        • 22 Install Kotlin plugins
          • 3 Creating a new project
            • 31 Create the project in Android Studio
            • 32 Configure Gradle
            • 33 Convert MainActivity to Kotlin code
            • 34 Test that everything works
              • 4 Classes and functions
                • 41 How to declare a class
                • 42 Class inheritance
                • 43 Functions
                • 44 Constructor and functions parameters
                  • 5 Writing your first class
                    • 51 Creating the layout
                    • 52 The Recycler Adapter
                      • Get the book