Programming Kotlin - Tephen Samuel - E-Book

Programming Kotlin E-Book

Tephen Samuel

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 542

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers 
What you need for this book 
Who this book is for 
Conventions 
Reader feedback
Customer support
Downloading the example code 
Downloading the color images of this book 
Errata
Piracy
Questions
1. Getting Started with Kotlin
Using the command line to compile and run Kotlin code
Kotlin runtime
The REPL
Kotlin for scripting
Kotlin with Gradle
Kotlin with Maven
IntelliJ and Kotlin
Eclipse and Kotlin
Mixing Kotlin and Java in a project
Summary
2. Kotlin Basics
Vals and vars
Type inference
Basic types
Numbers
Booleans
Chars
Strings
Arrays
Comments
Packages
Imports
Wildcard imports
Import renaming
String templates
Ranges
Loops
Exception handling
Instantiating classes
Referential equality and structural equality
This expression
Scope
Visibility modifiers
Private
Protected
Internal
Control flow as expressions
Null syntax
Smart casts
Explicit casting
When expression
When (value)
When without argument
Function Return
Type hierarchy
Summary
3. Object-Oriented Programming in Kotlin
Classes
Access levels
Nested classes
Data classes
Enum classes
Static methods and companion objects
Interfaces
Inheritance
Visibility modifiers
Abstract classes
Interface or abstract class
Polymorphism
Overriding rules
Inheritance versus composition
Class delegation
Sealed classes
Summary
4. Functions in Kotlin
Defining functions
Single expression functions
Member functions
Local functions
Top-level functions
Named parameters
Default parameters
Extension functions
Extension function precedence
Extension functions on nulls
Member extension functions
Overriding member extension functions
Companion object extensions
Multiple return values
Infix functions
Operators
Operator overloading
Basic operators
In/contains
Get/set
Invoke
Comparison
Assignment
Java interop
Function literals
Tail recursive functions
Varargs
Spread operator
Standard library functions
Apply
Let
With
Run
Lazy
Use
Repeat
Require/assert/check
Generic functions
Pure functions
Java from Kotlin
Getters and setters
Single abstract methods
Escaping Kotlin identifiers
Java void methods
Kotlin from Java
Top-level functions
Default parameters
Object and static methods
Erasure naming
Checked exceptions
Summary
5. Higher Order Functions and Functional Programming
Higher order functions
Returning a function
Function assignment
Closures
Anonymous functions
Function references
Top-level function references
Member and extension function references
Bound references
Function-literal receivers
Functions in the JVM
Bytecode
Function composition
Inline functions
Noinline
Currying and partial application
Currying in action
Adding currying support
Memoization
Implementing memoization
Type alias
Either
Fold
Projection
Further projection functions
Custom DSLs
Infix functions as keywords
Using function receivers in a DSL
Validation and error accumulation
Summary
6. Properties
Why use properties?
Syntax and variations
Visibility
Late initialization
Delegated properties
Lazy initializations
Lateinit versus lazy
Observables
A non-null property delegate
Properties or methods?
Summary
7. Null Safety, Reflection, and Annotations
Nullable types
Smart cast
Safe null access
Force operator
Elvis operator
Safe casting
Optionals
Creating and returning an Optional
Using an Optional
Reflection
KClass
Instantiation using reflection
Constructors
Instantiation with callBy
Objects and companions
Useful KClass properties
Reflective functions and properties
Invoking a function reflectively
Declared and undeclared
Annotations
Annotation parameters
Standard annotations
@JvmName
@JvmStatic
@Throws
@JvmOverloads
Runtime annotation discovery
Summary
8. Generics
Parameterised functions
Parameterized types
Bounded polymorphism
Upper bounds
Multiple bounds
Type variance
Invariance
Covariance
Covariant return
Contravariance
Variance overview
Nothing type
Type projection
Type erasure
Type reification
Recursive type bounds
Algebraic data types
Summary
9. Data Classes
Automatic creation of getters and setters
The copy method
toString out of the box
hashCode and equals methods generated for you
Destructed declarations
Destructing types
Data class definition rules
Limitations
Summary
10. Collections
Class hierarchy
Arrays
Lists
Maps
Sets
Read-only views
Indexed access
Sequences
Summary
11. Testing in Kotlin
Getting started
Choosing a spec
Matchers
String matchers
Collection matchers
Floating point matchers
Expecting exceptions
Combining matchers
Custom matchers
Inspectors
Interceptors
The test case interceptor
The spec interceptor
Project config
Property testing
Specifying a generator
A custom generator
Table-driven testing
Testing non-deterministic code
Tags, conditions, and config
Config
Conditions
Tags
One instance
Resources
Summary
12. Microservices with Kotlin
Definition
Drawbacks
Why microservices?
Lagom
Defining services
Implementing a Lagom service
Summary
13. Concurrency
Threads
Blocking
Creating a thread
Stopping a thread
Thread interrupts
CPU-bound versus I/O-bound
Deadlocks and livelocks
Executors
Race conditions
Monitors
Locks
Read-write locks
Semaphores
The bounded buffer problem
Concurrent collections
ConcurrentHashMap
A blocking queue
Atomic variables
CountDownLatch
Cyclic Barrier
Non-blocking I/O and asynchronous programming
Futures
Summary

Programming Kotlin

Programming Kotlin

Copyright © 2017 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: January 2017

Production reference: 1130117

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78712-636-7

www.packtpub.com

Credits

Authors

Stephen Samuel

Stefan Bocutiu

Copy Editor

Safis Editing

Reviewers

Antonios Chalkiopoulos

Alexander Hanschke

Project Coordinator

Vaidehi Sawant

Commissioning Editor

Aaron Lazar

Proofreader

Safis Editing

Acquisition Editor

Kirk D'costa

Sonali Vernekar

Indexer

 Tejal Daruwale Soni

Content Development Editor

Nikhil Borkar

Graphics

Abhinash Sahu

Technical Editor

Subhalaxmi Nadar

Production Coordinator

Shraddha Falebhai

About the Authors

Stephen Samuel is an accomplished developer with over 17 years of experience. He has worked with Java throughout his career, and in the past 5 years has focused on Scala. He has a passion for concurrency and Big Data technologies. Having spent the last few years in investment banking, he is currently working with Kotlin on a major Big Data ingestment project. Stephen is also active in the open source community, being the author of several high profile Scala and Kotlin libraries.

I would like to thank my wife for being patient with all the days and nights spent on the computer, developing. I would also like to thank Stefan for kindly agreeing to co-author this book with me.

Stefan Bocutiu is a Big Data consultant with over 13 years of experience in software development. He enjoys coding in Scala, C#, and has a passion for stream processing technologies. With the team at DataMountaineer--a consultancy company offering delivery of solutions for streaming/ fast data platforms - he focuses on providing scalable, unified, real-time data pipelines allowing reactive decision making, analytics, and Hadoop integration.

Stefan is passionate about motorsports, and while his racing skills are not good enough to allow him to compete, he tries to attend as many MotoGP races as possible. When he is not coding, he can be found at the climbing wall or at the gym. Occasionally, hiking and scrambling trips are on his calendar, and during the winter season, skiing trips are a must for him.

About the Reviewers

Antonios Chalkiopoulos is a distributed systems specialist, engineering Big Data systems in the past 5 years on Media, Betting, Retail, Investment Banks, and FinTech companies in London. He is the author of Programming MapReduce with Scalding, one of the first books presenting how Scala can be used for Big Data solutions, and an open source contributor to a number of projects.

He is the founder of LANDOOP, a company that specializes in Fast Data and Big Data solutions and provides numerous tools and capabilities around Apache Kafka and real-time streaming systems.

Alexander Hanschke is a co-founder and CTO at techdev Solutions GmbH, a software company based in Berlin. He graduated from University of Mannheim and has worked in the financial sector, building Java enterprise applications for 8 years.

At his company, these days Alex is working on web applications written in Java and Kotlin. He frequently talks at user groups and conferences and is writing about Kotlin-related topics.

You can find him on Twitter at @alexhanschke.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer Feedback

Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously—that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn. You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: [email protected].

Preface

Kotlin is typically associated with Android development, and most discussion about it revolves gravitates around that. But the language has much more to offer and is ideal for modern server side developers. While any Android developer will find useful snippets in this book, the book is targeting Java and Scala developers primarily. The book will start with a introduction to Kotlin and explain how you set up your environment before moving on to the basic concepts. Once the basics are out of the way, the focus will shift towards more advanced concepts, and don't be surprised if you see a few bytecode listings. Once you have completed the book you should have all the knowledge required to start using Kotlin for your next project. 

What this book covers 

Chapter 1, Getting Started with Kotlin, covers how to install Kotlin, the Jetbrains Intellij IDEA, and the Gradle build system. Once the setup of the tool chain is complete, the chapter shows how to write your first Kotlin program.

Chapter 2, Kotlin Basics, dives head first into the basics of Kotlin, including the basic types, basic syntax, and program control flow structures such as if statements, for loops, and while loops. The chapter concludes with Kotlin-specific additions such as when expressions and type inference.

Chapter 3, Object-Oriented Code in Kotlin, focuses on the object-orientated aspects of the language. It introduces classes, interfaces, objects and the relationship between them, subtypes, and polymorphism.

Chapter 4, Functions in Kotlin, shows that functions, also known as procedures or methods, are the basic building blocks of any language. This chapter covers the syntax for functions, including the Kotlin enhancements such as named parameters, default parameters, and function literals.

Chapter 5, Higher Order Functions and Functional Programming, focuses on the functional programming side of Kotlin, including closures--also known as lambdas--and function references. It further covers functional programming techniques such as partial application, function composition, and error accumulation.

Chapter 6, Properties, explains that properties work hand in hand with object-orientated programming to expose values on a class or object. This chapter covers how properties work, how the user can best make use of them, and also how they are represented in the bytecode.

Chapter 7, Null Safety, Reflection, and Annotations, explains that null safety is one of the main features that Kotlin provides, and the first part of this chapter covers in depth the whys and hows of null safety in Kotlin. The second part of the chapter introduces reflection--run time introspection of code--and how it can be used for meta programming with annotations.

Chapter 8, Generics, explains that generics, or parameterized types, are a key component of any advanced type system, and the type system in Kotlin is substantially more advanced than that available in Java. This chapter covers variance, the type system including the Nothing type, and algebraic data types.

Chapter 9, Data Classes, shows that immutability and boiler-plate free domain classes are a current hot topic, due to the way they facilitate more robust code and simplify concurrent programming. Kotlin has many features focused on this area, which it calls data classes.

Chapter 10, Collections, explains that collections are one of the most commonly used aspects of any standard library, and Java collections are no different. This chapter describes the enhancements that Kotlin has made to the JDK collections, including functional operations such as map, fold, and filter.

Chapter 11, Testing in Kotlin, explains that one of the gateways into any new language is using it as a language for writing test code. This chapter shows how the exciting test framework KotlinTest can be used to write expressive, human-readable tests, with much more power than the standard jUnit tests allow.

Chapter 12, Microservices in Kotlin, shows that microservices have come to dominate server-side architecture in recent years, and Kotlin is an excellent choice for writing such services. This chapter introduces the Lagom microservice framework and shows how it can be used to great effect with Kotlin.

Chapter 13, Concurrency, explains that as multi-core aware programs are becoming more and more important in server-side platforms, This chapter is focused on a solid introduction to concurrent programming techniques that are vital in modern development, including threads, concurrency primitives, and futures.

What you need for this book 

This book requires a computer running MacOS, Linux, or Windows, capable of running the latest versions of Java. It is recommended that the machine has enough memory to run a recent version of Jetbrains' Intellij IDEA.

Who this book is for 

This book is aimed those who have little or no Kotlin experience and wish to learn the language quickly. The focus of the book is on server-side development in Kotlin and would be best suited to a developer who is currently a server-side developer or who wishes to learn. No prior knowledge of functional or object-orientated programming is required, but knowledge of some other programming language is recommended.

Some chapters contain brief sections comparing Java implementations to their Kotlin cousins, but these pages can be skipped by those who have no prior Java knowledge.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code 

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Programming-Kotlin. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book 

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/ProgrammingKotlin_ColorImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

Chapter 1. Getting Started with Kotlin

It is time to write code. In this chapter, we will go over and write the typical entry code for every language: the famous Hello World! In order to do that, we will need to set up the initial environment required to develop software with Kotlin. We will provide a few examples using the compiler from the command line, and then we will move towards the typical way of programming using the IDEs and build tools available.

Kotlin is a JVM language, and so the compiler will emit Java bytecode. Because of this, of course, Kotlin code can call Java code, and vice versa! Therefore, you need to have the Java JDK installed on your machine. To be able to write code for Android, where the most recent supported Java version is 6, the compiler needs to translate your code to bytecode that is compatible at least with Java 6. For this book, however, all the code examples will be run with Java JDK 8. If you are new to the JVM world, you can get the latest version from http://www.oracle.com/technetwork/java/javase/downloads/index.html.

In this chapter you will learn how to:

Use the command line to compile and execute code written in KotlinUse the REPL and write Kotlin scriptsCreate a gradle project with Kotlin enabledCreate a Maven project with Kotlin enabledUse IntelliJ to create a Kotlin projectUse Eclipse IDE to create a Kotlin projectMix Kotlin and Java code in the same project

Using the command line to compile and run Kotlin code

To write and execute code written in Kotlin, you will need its runtime and the compiler. At the time of writing, version 1.1 milestone 4 is available (the stable release is 1.0.6). Every runtime release comes with its own compiler version. To get your hands on it, navigate to https://github.com/JetBrains/kotlin/releases/tag/v1.1-M04, scroll to the bottom of the page, and download and unpack the ZIP archive kotlin-compiler-1.1-M04.zip to a known location on your machine. The output folder will contain a subfolder bin with all the scripts required to compile and run Kotlin on Windows, Linux, or OS X. Now you need to make sure the bin folder location is part of your system PATH in order to call the kotlinc without having to specify the full path.

If your machine runs Linux or OS X, there is an even easier way to install the compiler by using sdkman. All you need to do is execute the following commands in a terminal:

$ curl -s https://get.sdkman.io | bash$ bash$ sdk install kotlin 1.1-M04

Alternatively, if you are using OS X and you have homebrew installed, you could run these commands to achieve the same thing:

$ brew update

$ brew install  [email protected]

Now that all of this is done, we can finally write our first Kotlin code. The application we will be writing does nothing else but display the text Hello World! on the console. Start by creating a new file named HelloWorld.kt and type the following:

fun main(args: Array<String>) { println("Hello, World!") }

From the command line, invoke the compiler to produce the JAR assembly (include-runtime is a flag for the compiler to produce a self-contained and runnable JAR by including the Kotlin runtime into the resulting assembly):

kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar

Now you are ready to run your program by typing the following on your command line; it is assumed your JAVA_HOME is set and added to the system path:

$ java -jar HelloWorld.jar

The code is pretty straight forward. It defines the entry point function for your program, and in the first and only line of code, it prints the text to the console.

If you have been working with the Java or Scala languages, you might raise an eyebrow because you noticed the lack of the typical class that would normally define the standard static main program entry point. How does it work then? Let's have a look at what actually happens. First, let's just compile the preceding code by running the following command. This will create a HelloWorld.class in the same folder:

$ kotlinc HelloWorld.kt

Now that we have the bytecode generated, let's look at it by using the javap tool available with the JDK (please note that the file name contains a suffix Kt):

$ javap -c HelloWorldKt.class

Once the execution completes, you should see the following printed on your terminal:

Compiled from "HelloWorld.kt"public final class HelloWorldKt { public static final void main(java.lang.String[]); Code: 0: aload_0 1: ldc #9 // String args 3: invokestatic #15 // Method kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull:(Ljava/lang/Ob ject;Ljava/lang/String;)V 6: ldc #17 // String Hello, World! 8: astore_1 9: nop 10: getstatic #23 // Field java/lang/System.out:Ljava/io/PrintStream; 13: aload_1 14: invokevirtual #29 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V 17: return}

You don't have to be an expert in bytecode to understand what the compiler has actually done for us. As you can see on the snippet, a class has been generated for us, and it contains the program entry point with the instructions to print Hello World! to the console.

I would not expect you to work with the command line compiler on a daily basis; rather, you should  use the tools at hand to delegate this, as we will see shortly.

Kotlin runtime

When we compiled Hello World! and produced the JAR, we instructed the compiler to bundle in the Kotlin runtime. Why is the runtime needed? Take a closer look at the bytecode generated, if you haven't already. To be more specific, look at line 3. It invokes a method to validate that the args variable is not null; thus, if you compile the code without asking for the runtime to be bundled in and try to run it, you will get an exception.

$ kotlinc HelloWorld.kt -d HelloWorld.jar$ java -jar HelloWorld.jarException in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsicsat HelloWorldKt.main(HelloWorld.kt)Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics

The runtime footprint is very small; with ~800 K one can't argue otherwise. Kotlin comes with its own standard class library (Kotlin runtime), which is different from the Java library. As a result, you need to merge it into the resulting JAR, or provide it in the classpath:

$ java -cp $KOTLIN_HOME/lib/kotlin-runtime.jar:HelloWorld.jar HelloWorldKt

If you develop a library for the exclusive use of other Kotlin libraries or applications, then you don't have to include the runtime. Alternatively there is a shorter path. This is done via a flag passed to the Kotlin compiler:

$kotlinc -include-runtime HelloWorld.kt -d HelloWorld

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 prefer to quickly test their methods, but you should always write unit tests rather than using the REPL to validate that the output is correct.

You can start the REPL by adding dependencies to the classpath in order to make them available within the instance. To give 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:

$ kotlinc-jvm -cp joda-time-2.9.4/joda-time-2.9.4.jarWelcome 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

Kotlin with Maven

If you still prefer to stick with good old Maven, there is no problem. There is a plugin for it to support Kotlin as well. If you don't have Maven on your machine, you can follow the instructions at https://maven.apache.org/install.html to get it installed on your local machine.

Just as we did with Gradle, let's use the built-in templates to generate the project folder and file structure. From the terminal, within a brand new folder, you will have to run the following command:

$ mvn archetype:generate -DgroupId=com.programming.kotlin - DartifactId=chapter01 -DarchetypeArtifactId=maven-archetype- quickstart -DinteractiveMode=false

This will generate the pom.xml file and the src folder for Maven. But before we add the file containing the kotlin code, we need to enable the plugin. Just as before, start by deleting App.java and AppTest.java from src/main/java/com/programming/kotlin and test/main/java/com/programming/kotlin/, and create the src/kotlin folder (the subdirectory structure matches the namespace name):

$ mkdir -p src/main/kotlin/com/programming/kotlin/chapter01$ mkdir -p src/test/kotlin/com/programming/kotlin/chapter01

In an editor of your choice, open up the generated pom.xml file and add the following:

<pluginRepositories> <pluginRepository> <snapshots> <enabled>true</enabled> </snapshots> <id>bintray-kotlin-kotlin-dev</id> <name>bintray</name> <url>http://dl.bintray.com/kotlin/kotlin-dev</url> </pluginRepository> </pluginRepositories> <repositories> <repository> <snapshots> <enabled>true</enabled> </snapshots> <id>bintray-kotlin-kotlin-dev</id> <name>bintray</name> <url>http://dl.bintray.com/kotlin/kotlin-dev</url> </repository> </repositories> <properties> <kotlin.version>1.1-M04</kotlin.version> <kotlin.test.version>1.3.3</kotlin.test.version> </properties> <build> <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirecto ry> <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourc eDirectory> <plugins> <plugin> <artifactId>kotlin-maven-plugin</artifactId> <groupId>org.jetbrains.kotlin</groupId> <version>${kotlin.version}</version> <executions> <execution> <id>compile</id> <phase>process-sources</phase> <goals> <goal>compile</goal> </goals> </execution> <execution> <id>test-compile</id> <phase>process-test-sources</phase> <goals> <goal>test-compile</goal> </goals> </execution> </executions> </plugin> </plugins> </build>

All we have done so far is to enable the Kotlin plugin and make it run in the process-stages phase to allow the mixing of Java code as well. There are cases when you might have part of the source code written in good old Java. I am sure you also noticed the addition of source directory tags, allowing for the kotlin files to be included in the build.

The only thing left to do now is to add the library dependencies for the Kotlin runtime as well as the unit tests. We are not going to touch upon the testing framework until later in the book. Replace the entire dependencies section with the following:

<dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>${kotlin.version}</version> </dependency> <dependency> <groupId>io.kotlintest</groupId> <artifactId>kotlintest</artifactId> <version>${kotlin.test.version}</version> <scope>test</scope> </dependency> </dependencies>

It is time now to add the Hello World! code; this step is similar to the one we took earlier when we discussed Gradle:

$ echo "" >> src/main/kotlin/com/programming/kotlin/chapter01/Program.kt$cat <<EOF >> src/main/kotlin/com/programming/kotlin/chapter01/Program.kt package com.programming.kotlin.chapter01 fun main(args: Array<String>) { println("Hello World!") }

We are now in a position to compile and build the JAR file for the sample program:

$ mvn package$ mvn exec:java - Dexec.mainClass="com.programming.kotlin.chapter01.ProgramKt"

The last instruction should end up printing the Hello World! text to the console. Of course we can run the program outside Maven by going back to executing Java, but we need to add the Kotlin runtime to the classpath:

$java -cp $KOTLIN_HOME/lib/kotlin-runtime.jar:target/chapter01-1.0- SNAPSHOT.jar "com.programming.kotlin.chapter01.ProgramKt"

If you want to avoid the Classpath dependency setup when you run the application, there is an option to bundle all the dependencies in the resulted JAR and produce what is called a fat jar. For that, however, another plugin needs to be added:

<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.4.3</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestRe sourceTransformer"> <mainClass>com.programming.kotlin.chapter01.ProgramKt</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin>

We can execute the command to run our JAR without having to worry about setting the classpath since this has been taken care of by the plugin:

$ java -jar target/chapter01-1.0-SNAPSHOT.jar

IntelliJ and Kotlin

Coding using Vim/nano is not everyone's first choice; working without the help of an IDE with its code completion, intelli-sense, shortcuts for adding files, or refactoring code can prove challenging the more complex the project is.

For a while now, in the JVM world, people's first choice when it comes to their integrated development environment has been IntelliJ. The tool is made by the same company that created Kotlin: JetBrains. Given the integration between the two of them, it would be my first choice of IDE to use, but, as we will see in the next section it is not the only option.

IntelliJ comes in two versions: Ultimate and Community (free). For the code we will be using in the course of this book, the free version is enough. If you don't have it already installed, you can download it from https://www.jetbrains.com/idea/download.

From version 15.0, IntelliJ comes bundled with Kotlin, but if you have an older version you can still get support for the language by installing the plugin. Just go to Settings|Plugins| Install IntelliJ plugins and type Kotlin in the search.

We are going to use the IDE to create a Gradle project with Kotlin enabled, just as we did in the previous section. Once you have started IntelliJ, you will have to choose Create new project. You will get a dialog window from which you should select Gradle from the left-hand side section; check the Kotlin(Java) option from the right-hand side. As you can see here:

Selecting a project type

You should already have the system variable JAVA_HOME set up for the tool to pick it up automatically (see the Project SDK at the top of the screenshot). If this isn't the case, choose the New button and navigate to where your Java JDK is. Once you have selected it, you are ready to go to the next step by clicking on the Next button available on the bottom right-hand side of the screen.

The next window presented to you is asking you to provide the Group Id and Artifact Id. Let's go with com.programming.kotlin and chapter01 respectively. Once you have completed the fields, you can move to the next step of the process where you tick the Use auto-import flag as well as Create directories for empty directory roots automatically. Now carry on to the next step, where you are asked where you wish to store the project on your machine. Set the project location, expand More Settings, type chapter01 for the Module name, and hit the Finish button.

IntelliJ will go on and create the project, and you should have the outcome shown in the following screenshot:

Hello World! basic project

On the selected kotlin folder, right-click and choose the New | Package option, and type com.programming.kotlin.chapter01:

Setting up the package name

Below the kotlin folder, you should see a new one appear, matching what was typed earlier. Right click on that, choose New | Kotlin File/Class, and type Program.kt:

Creating Program.kt file

We are now ready to start typing our Hello World! Use the same code we created earlier in the chapter. You should notice the Kotlin brand icon on the left-hand side of the file editor. If you click on it, you will get the option to run the code, and if you look at the bottom of your IntelliJ window you should see the text Hello World! printed out:

Hello World! program

Well done! You have written your first Kotlin program. It was easy and quick to set up the project and code, and to run the program. If you prefer, you can have a Maven rather than a Gradle project. When you choose New | Project, you have to select Maven from the left-hand side and check Create from archetype while choosing org.jetbrains.kotlin:kotlin-archetype-jvm from the list presented:

Maven project

Eclipse and Kotlin

There might be some of you who still prefer Eclipse IDE to IntelliJ; don't worry, you can still develop Kotlin code without having to move away from it. At this point, I assume you already have the tool installed. From the menu, navigate to Help | Eclipse Marketplace, look for the Kotlin plugin, and install it (I am working with the latest distribution: Eclipse Neon).

Once you have installed the plugin and restarted the IDE, you are ready to create your first Kotlin project. From the menu, choose File | New | Project and you should see the following dialog:

New Kotlin project

Click the Next button to move to the next step and, once you have chosen the source code location, click the Finish button. This is not a Gradle or Maven project! You can choose one of the two, but then you will have to manually modify the build.gradle or pom.xml, as we did manually in the Kotlin with Gradle and Kotlin with Maven sections of this chapter. Similar to the IntelliJ project, click on the src folder, choose New package, and name it com.programming.kotlin.chapter01. To add our Program.kt, you will need to right-click on the newly created package, select New | Other, and select Kotlin | Kotlin File from the list. Once the file has been created, type the simple lines of code to print out the text to the console. You should have the following result in your Eclipse IDE:

Hello World! with Eclipse

Now you are ready to run the code. From the menu select Run | Run. You should be able to trigger the execution, and in the Console tab at the bottom of your IDE you should see the Hello World! text printed out.

Summary

This chapter has showed you how you can set up your development environment with the tools required to build and run Kotlin code. Now you are able to run and execute the examples created in the rest of the book, as well as experiment with your own Kotlin code.

In the next chapter you will delve into the basic constructs you will use daily when you code in Kotlin.

Comments

Comments in Kotlin will come as no surprise to most programmers as they are the same as Java, Javascript, and C, among other languages. Block comments and line comments are supported:

// line comment /* A block comment can span many lines */

Imports

To enable classes, objects, interfaces, and functions to be used outside of the declared package we must import the required class, object, interface, or function:

import com.packt.myproject.Foo

Wildcard imports