Book Image

Learn Kotlin Programming - Second Edition

By : Stephen Samuel, Stefan Bocutiu
Book Image

Learn Kotlin Programming - Second Edition

By: Stephen Samuel, Stefan Bocutiu

Overview of this book

Kotlin is a general-purpose programming language used for developing cross-platform applications. Complete with a comprehensive introduction and projects covering the full set of Kotlin programming features, this book will take you through the fundamentals of Kotlin and get you up to speed in no time. Learn Kotlin Programming covers the installation, tools, and how to write basic programs in Kotlin. You'll learn how to implement object-oriented programming in Kotlin and easily reuse your program or parts of it. The book explains DSL construction, serialization, null safety aspects, and type parameterization to help you build robust apps. You'll learn how to destructure expressions and write your own. You'll then get to grips with building scalable apps by exploring advanced topics such as testing, concurrency, microservices, coroutines, and Kotlin DSL builders. Furthermore, you'll be introduced to the kotlinx.serialization framework, which is used to persist objects in JSON, Protobuf, and other formats. By the end of this book, you'll be well versed with all the new features in Kotlin and will be able to build robust applications skillfully.
Table of Contents (21 chapters)
Free Chapter
1
Section 1: Fundamental Concepts in Kotlin
5
Section 2: Practical Concepts in Kotlin
15
Section 3: Advanced Concepts in Kotlin

The REPL

These days, most languages provide an interactive shell, and Kotlin is no exception. If you want to quickly write some code that you won't use again, then the REPL is a good tool to have. Some people prefer to test their methods quickly, but you should always write unit tests rather than using the REPL to validate that the output is correct.

Note: REPL is the common name when referring to an interactive shell, and is an abbreviation for read, evaluate, print, loop.

You can start the REPL by adding dependencies to the classpath in order to make them available within the instance. To look at an example, we will use the Joda library to deal with the date and time. First, we need to download the JAR. In a Terminal window, use the following commands:

$ wget https://github.com/JodaOrg/joda-time/releases/download/v2.9.4/joda-time-2.9.4-dist.tar.gz
$ tar xvf joda-time-2.9.4-dist.tar.gz

Now, you are ready to start the REPL. Attach the Joda library to its running instance, and import and use the classes it provides, as follows:

$ kotlinc-jvm -cp joda-time-2.9.4/joda-time-2.9.4.jar
Welcome to Kotlin version 1.1-M04 (JRE 1.8.0_66-internal-b17)
Type :help for help, :quit for quit
>>> import org.joda.time.DateTime
>>> DateTime.now()
2016-08-25T22:53:41.017+01:00

Running the preceding code will execute the now function of the DateTime class provided by the Joda library. The output is simply the current date and time.