Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Android Development with Kotlin

You're reading from   Android Development with Kotlin Enhance your skills for Android development using Kotlin

Arrow left icon
Product type Paperback
Published in Aug 2017
Publisher Packt
ISBN-13 9781787123687
Length 440 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Marcin Moskala Marcin Moskala
Author Profile Icon Marcin Moskala
Marcin Moskala
Igor Wojda Igor Wojda
Author Profile Icon Igor Wojda
Igor Wojda
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Beginning Your Kotlin Adventure FREE CHAPTER 2. Laying a Foundation 3. Playing with Functions 4. Classes and Objects 5. Functions as First-Class Citizens 6. Generics Are Your Friends 7. Extension Functions and Properties 8. Delegates 9. Making Your Marvel Gallery Application

Dealing with Kotlin code

There are multiple ways of managing and running Kotlin code. We will mainly focus on Android Studio and Kotlin Playground.

Kotlin Playground

The fastest way to try Kotlin code without the need to install any software is Kotlin Playground (https://try.kotlinlang.org). We can run Kotlin code there using JavaScript or JVM Kotlin implementations and easily switch between different Kotlin versions. All the code examples from the book that does not require Android framework dependencies and can be executed using Kotlin Playground.

The main function is the entry point of every Kotlin application. This function is called when any application starts, so we must place code from the book examples in the body of this method. We can place code directly or just place a call to another function containing more Kotlin code:

    fun main(args: Array<String>) { 
        println("Hello, world!") 
    }
Android applications have multiple entry points. The main function is called implicitly by the Android framework, so we can't use it to run Kotlin code on the Android platform.

Android Studio

All Android Studio's existing tools work with Kotlin code. We can easily use debugging, lint checks, have proper code assistance, refactoring, and more. Most of the things work the same way as for Java, so the biggest noticeable change is the Kotlin language syntax. All we need to do is to configure Kotlin in the project.

Android applications have multiple entry points (different intents can start different components in the application) and require Android framework dependencies. To run the book examples, we need to extend the Activity class and place code there.

Configuring Kotlin for the project

Starting from Android Studio 3.0, full tooling support for Kotlin was added. Installation of the Kotlin plugin is not required and Kotlin is integrated even deeper into the Android development process.

To use Kotlin with Android Studio 2.x, we must manually install the Kotlin plugin. To install it, we need to go to Android Studio | File | Settings | Plugins | Install JetBrains plugin... | Kotlin and press the Install button:

To be able to use Kotlin, we need to configure Kotlin in our project. For existing Java projects, we need to run the Configure Kotlin in project action (the shortcut in Windows is Ctrl+Shift+A, and in macOS, it is command + shift + A) or use the corresponding Tools | Kotlin | Configure Kotlin in Project menu item:

Then, select Android with Gradle:

Finally, we need to select the required modules and the proper Kotlin version:

The preceding configuration scenario also applies to all existing Android projects that were initially created in Java. Starting from Android Studio 3.0, we can also check the Include Kotlin support checkbox while creating a new project:

In both scenarios, the Configure Kotlin in project command updates the root build.gradle file and the build.gradle files corresponding to the module(s) by adding Kotlin dependencies. It also adds the Kotlin plugin to the Android module. At the time of writing this book release version of Android Studio 3 is not yet available, but we can review the build script from the pre-release version:

//build.gradle file in project root folder 
buildscript { 
    ext.kotlin_version = '1.1' 
 
    repositories { 
        google() 
        jcenter() 
    } 
    dependencies { 
       classpath 'com.android.tools.build:gradle:3.0.0-alpha9' 
       classpath "org.jetbrains.kotlin:kotlin-gradle-
plugin:$kotlin_version" } }
... //build.gradle file in the selected modules apply plugin: 'com.android.application' apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
... dependencies { ...
implementation 'com.android.support.constraint:constraint-
layout:1.0.2'
} ...
Prior to the Android plugin for Gradle 3.x (delivered with Android Studio 3.0), compile dependency configuration was used instead of implementation.

To update the Kotlin version (let us say in the future), we need to change the value of the kotlin_version variable in the build.gradle file (project root folder). Changes in Gradle files mean that the project must be synchronized, so Gradle can update its configuration and download all the required dependencies:

Using Kotlin in a new Android project

For new Kotlin projects created in Android Studio 3.x, the main activity will be already defined in Kotlin, so that we can start writing Kotlin code right away:

Adding a new Kotlin file is similar to adding a Java file. Simply right-click on a package and select new | Kotlin File/Class:

The reason why the IDE says Kotlin File/Class and not simply Kotlin class, which is analogous to Java class, is that we can have more members defined inside a single file. We will discuss this in more detail in Chapter 2, Laying a Foundation.

Notice that Kotlin source files can be located inside the java source folder. We can create a new source folder for Kotlin, but it is not required:

Running and debugging a project is exactly the same as in Java and does not require any additional steps besides configuring Kotlin in the project:

Starting from Android Studio 3.0, various Android templates will also allow us to select a language. This is the new Configure Activity wizard:

Java to Kotlin converter (J2K)

Migration of existing Java projects is also quite easy, because we can use Java and Kotlin side by side in the same project. There are also ways to convert existing Java code into Kotlin code by using the Java to Kotlin converter (J2K).

The first way is to convert whole Java files into Kotlin files using the convert Java File to Kotlin command (the keyboard shortcut in Windows is Alt + Shift + Ctrl + K and in macOS is option + shift + command + K), and this works very well. The second way is to paste Java code into an existing Kotlin file and the code will also be converted (a dialog window will appear with a conversion proposition). This may be very helpful when learning Kotlin.

If we don't know how to write a particular piece of code in Kotlin, we can write it in Java, then simply copy to the clipboard and paste it into the Kotlin file. Converted code will not be the most idiomatic version of Kotlin, but it will work. The IDE will display various intentions to convert the code even more and improve its quality. Before conversion, we need to make sure that the Java code is valid, because conversion tools are very sensitive and the process will fail even if a single semicolon is missing. The J2K converter combined with Java interoperability allows Kotlin be introduced gradually into the existing project (for example, to convert a single class at a time).

Alternative ways to run Kotlin code

Android Studio offers an alternative way of running Kotlin code without the need to run the Android application. This is useful when you want to quickly test some Kotlin code separately from the long Android compilation and deployment process.

The way to run Kotlin code is to use the Kotlin Read Eval Print Loop (REPL). REPL is a simple language shell that reads single user input, evaluates it, and prints the result:

REPL looks like the command-line, but it will provide us with all the required code hints and will give us access to various structures defined inside the project (classes, interfaces, top-level functions, and so on):

The biggest advantage of REPL is its speed. We can test Kotlin code really quickly.

You have been reading a chapter from
Android Development with Kotlin
Published in: Aug 2017
Publisher: Packt
ISBN-13: 9781787123687
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image