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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Kotlin Quick Start Guide
Kotlin Quick Start Guide

Kotlin Quick Start Guide: Core features to get you ready for developing applications

Arrow left icon
Profile Icon Marko Devcic
Arrow right icon
€18.99 per month
Paperback Aug 2018 178 pages 1st Edition
eBook
€13.98 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Marko Devcic
Arrow right icon
€18.99 per month
Paperback Aug 2018 178 pages 1st Edition
eBook
€13.98 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€13.98 €19.99
Paperback
€24.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Kotlin Quick Start Guide

Kotlin Basics

With Kotlin IDE installed, it is now time to start learning the basic elements of the language. In this chapter, you can learn about local variables and functions and basic Kotlin Types. If you are a Java programmer, in this chapter you'll see what sets Kotlin apart from Java. You'll see how type inference works and how Kotlin, with its support for Nullable Types, tries to prevent NullPointerExceptions.

Here is the complete overview of topics you will learn in this chapter:

  • Functions
  • Local variables
  • Local functions
  • Type inference
  • Basic types
  • Nullable types
  • Casting
  • Control flow
  • Exceptions
  • Packages
  • Visibility modifiers

Functions

Functions in Kotlin are declared with the fun keyword. Following the keyword comes the function name, then parentheses, which contain optional function parameters. In Kotlin, return type comes at the end of the function definition, after a colon.

Here's a function in Kotlin that adds two numbers and returns the result:

fun add(a: Int, b: Int): Int {
val result: Int = a + b
return result
}

This function accepts two parameters of type Int (32-bit integer), has a local variable of type Int, and also returns an Int.

If you are familiar with Java, you might have noticed that types of parameters and local variables come after their name. In Java their type declaration comes first.

Calling this function would look like this:

val result: Int = add(1, 1)

In Java, every declaration, such as a field or a function, has to be inside a class. Kotlin doesn’t have...

Local variables

Local variables can be declared in two ways: first, with the val  keyword, then they are immutable (the variable cannot be reassigned). If you are coming from Java, val would be equal to variables declared with a final keyword.

Secondly, you can declare a local variable with a var keyword; then it is considered mutable and the value can be reassigned after a declaration.

The following command demonstrates that it will not compile, because the bar local variable cannot be reassigned:

fun immutable() {
val bar: String = "Kotlin"
bar = "Kotlin is awesome" // compiler error
}

And, when declared with var, the compiler allows a local variable to be reassigned:

fun mutable() {
var bar: String = "Kotlin"
bar = "Kotlin is awesome"
}

You should favor immutable variables. The compiler will...

Local functions

Local functions are functions declared inside a function. They are also called nested functions. They are popular in scripting languages, but some other modern Object-Oriented languages, like Scala, Swift, and C# (since 7.0) also have them. One of the uses of local functions is code reuse. You can extract a piece of code that is repeated inside a local function so the code can be reused:

fun printUserDetails(user: User) {
fun tryPrint(str: String) {
if (str.length > 5) {
println(str)
}
else {
println("I print strings with more than 5 characters")
}
}
tryPrint(user.firstName)
tryPrint(user.lastName)
tryPrint(user.address)
}

You can see how the function tryPrint is declared inside the printUserDetails function.  We can call the nested function just as we would a normal function...

Type inference

Declaring types in Kotlin is optional. This is a feature of a Kotlin compiler called Type inference. The compiler can infer the type from the context of the usage. Kotlin is a strongly and statically typed language, so omitting types doesn’t mean that you lose type safety. 

Here’s an example of type inference:

val str = "Kotlin"

str variable is of type String and the compiler knows this from the String literal that is initializing the variable. That’s why, if you try to assign a different type to this variable, you'll get a compiler error, as can be seen in the following:

var str = "Kotlin"
str = 1 // compiler error

Type inference doesn’t just work on local variables, but also on functions with expression bodies, generic types, closures and lambdas. You’ll see more type inference in practice in following...

Basic types

If you are familiar with Java, then you probably know that Java has primitive (value) types and reference types.

The differences between them are that primitive type variables store the actual value of the type in their memory location (usually on the Stack) and reference type variables store the reference (memory address) to another memory location (on the Heap) where the actual data is stored.

Primitive types in Java also have their Boxed (Boxing is an automatic conversion of a primitive type to a reference type) version, a reference type. For example, a primitive int (32-bit integer) has a reference type in type Integer.

Kotlin doesn’t have this distinction between primitive and reference type. This doesn’t mean a Kotlin compiler cannot emit primitive types in Java bytecode. In fact, it would be really inefficient if Kotlin had only reference...

Nullable types

When you want to state that a reference type doesn’t point to a memory address, you can assign it a null value. If you have ever used Java, you probably experienced the NullPointerException fail, as it is one of the most common errors. This error is raised by the runtime when you dereference a null variable.

This decision, to have nulls in Java, is criticized a lot and is also sometimes called  a Billion Dollar mistake. The introduction of the optional type in Java 8, tries to address this problem.

Kotlin tries to prevent these mistakes with supporting nullability in its type system. With nullable types, Kotlin tries to prevent null pointer errors during compilation and reduce the possibility of null pointer errors during runtime.

All types in Kotlin can be nullable, and only then can they have a null value assigned. Nullable types are declared with...

Casting

To cast from one type to another, Kotlin uses the as keyword. Here’s how you would cast Any type to an Int type:

fun casting(any: Any) {
val num = any as Int
}

During runtime, before casting, the JVM will check if the source type can be cast to target type. If not, ClassCastException will be thrown.

Safe casting

There is also the safe casting operator, as?. This operator checks, before casting, whether or not types are compatible. If they are, then it works as a normal asoperator. If not, a null value is assigned. Notice how in this example, the local variable num has to be declared as a nullable type:

fun safeCasting(any: Any) {
val num: Int? = any as? Int
}

Safe casts can be used with all other null...

Functions


Functions in Kotlin are declared with the fun keyword. Following the keyword comes the function name, then parentheses, which contain optional function parameters. In Kotlin, return type comes at the end of the function definition, after a colon.

Here's a function in Kotlin that adds two numbers and returns the result:

fun add(a: Int, b: Int): Int {
val result: Int = a + b 
return result
}

This function accepts two parameters of type Int (32-bit integer), has a local variable of type Int, and also returns an Int.

If you are familiar with Java, you might have noticed that types of parameters and local variables come after their name. In Java their type declaration comes first.

Calling this function would look like this:

val result: Int = add(1, 1)

In Java, every declaration, such as a field or a function, has to be inside a class. Kotlin doesn’t have such restrictions and will allow you to declare functions on a file level, outside of a class. To make it compatible with Java bytecode,...

Local variables


Local variables can be declared in two ways: first, with the val  keyword, then they are immutable (the variable cannot be reassigned). If you are coming from Java, val would be equal to variables declared with a final keyword.

Secondly, you can declare a local variable with a var keyword; then it is considered mutable and the value can be reassigned after a declaration.

The following command demonstrates that it will not compile, because the bar local variable cannot be reassigned:

fun immutable() {
val bar: String = "Kotlin"
bar = "Kotlin is awesome" // compiler error
}

And, when declared with var, the compiler allows a local variable to be reassigned:

fun mutable() {
var bar: String = "Kotlin"
bar = "Kotlin is awesome" 
}

You should favor immutable variables. The compiler will give you a warning if you use a mutable variable but only assign it once.

Whether you declare a variable as mutable or immutable, it has to have a value when it is declared, or, if it doesn’t have a value...

Local functions


Local functions are functions declared inside a function. They are also called nested functions. They are popular in scripting languages, but some other modern Object-Oriented languages, like Scala, Swift, and C# (since 7.0) also have them. One of the uses of local functions is code reuse. You can extract a piece of code that is repeated inside a local function so the code can be reused:

fun printUserDetails(user: User) {
fun tryPrint(str: String) {
if (str.length > 5) {
            println(str)
        } 
       else  {
println("I print strings with more than 5 characters")
       }
    }
    tryPrint(user.firstName)
tryPrint(user.lastName)
tryPrint(user.address)
}

You can see how the function tryPrint is declared inside the printUserDetails function.  We can call the nested function just as we would a normal function. The only difference between this and regular functions is the visibility. Local functions are only visible inside the function they were declared in. You...

Type inference


Declaring types in Kotlin is optional. This is a feature of a Kotlin compiler called Type inference. The compiler can infer the type from the context of the usage. Kotlin is a strongly and statically typed language, so omitting types doesn’t mean that you lose type safety. 

Here’s an example of type inference:

val str = "Kotlin"

str variable is of type String and the compiler knows this from the String literal that is initializing the variable. That’s why, if you try to assign a different type to this variable, you'll get a compiler error, as can be seen in the following:

var str = "Kotlin"
str = 1 // compiler error

Type inference doesn’t just work on local variables, but also on functions with expression bodies, generic types, closures and lambdas. You’ll see more type inference in practice in following chapters.

Basic types


If you are familiar with Java, then you probably know that Java has primitive (value) types and reference types.

The differences between them are that primitive type variables store the actual value of the type in their memory location (usually on the Stack) and reference type variables store the reference (memory address) to another memory location (on the Heap) where the actual data is stored.

Primitive types in Java also have their Boxed (Boxing is an automatic conversion of a primitive type to a reference type) version, a reference type. For example, a primitive int (32-bit integer) has a reference type in type Integer.

Kotlin doesn’t have this distinction between primitive and reference type. This doesn’t mean a Kotlin compiler cannot emit primitive types in Java bytecode. In fact, it would be really inefficient if Kotlin had only reference types.

Kotlin only hides this distinction from a developer. The compiler emits Java bytecode according to usage. In most cases, it will...

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Start programming with Kotlin
  • Explore Kotlin language syntax, standard libraries and Java Interoperability
  • Builds an example application with what you learn

Description

Kotlin is a general purpose, object-oriented language that primarily targets the JVM and Android. Intended as a better alternative to Java, its main goals are high interoperability with Java and increased developer productivity. Kotlin is still a new language and this book will help you to learn the core Kotlin features and get you ready for developing applications with Kotlin. This book covers Kotlin features in detail and explains them with practical code examples.You will learn how to set up the environment and take your frst steps with Kotlin and its syntax. We will cover the basics of the language, including functions, variables, and basic data types. With the basics covered, the next chapters show how functions are first-class citizens in Kotlin and deal with the object-oriented side of Kotlin. You will move on to more advanced features of Kotlin. You will explore Kotlin's Standard Library and learn how to work with the Collections API. The book finishes by putting Kotlin in to practice, showing how to build a desktop app. By the end of this book, you will be confident enough to use Kotlin for your next project.

Who is this book for?

This book is intended for anybody who wants to learn the most important Kotlin features. No experience of Kotlin is expected.

What you will learn

  • • Programming in Kotlin language syntax, basic types, control ?ow, classes, and OOP
  • • Writing functions and functional programming in Kotlin
  • • Defning and importing from packages in Kotlin
  • • Running Kotlin on JVMs and Android runtimes
  • • Working with the Kotlin Standard Library and advanced features of Kotlin programming
  • • Setting up a Kotlin development environment with JetBrains tools
  • • Building real-world applications with Kotlin

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 31, 2018
Length: 178 pages
Edition : 1st
Language : English
ISBN-13 : 9781789344189
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Aug 31, 2018
Length: 178 pages
Edition : 1st
Language : English
ISBN-13 : 9781789344189
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 99.97
Kotlin Programming Cookbook
€41.99
Kotlin Standard Library Cookbook
€32.99
Kotlin Quick Start Guide
€24.99
Total 99.97 Stars icon

Table of Contents

8 Chapters
Introducing Kotlin Chevron down icon Chevron up icon
Kotlin Basics Chevron down icon Chevron up icon
Classes and Object-Oriented Programming Chevron down icon Chevron up icon
Functions and Lambdas Chevron down icon Chevron up icon
Advanced Kotlin Chevron down icon Chevron up icon
Kotlin Standard Library Chevron down icon Chevron up icon
Coding a Dictionary App with Kotlin Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.