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
Conferences
Free Learning
Arrow right icon
Programming Kotlin
Programming Kotlin

Programming Kotlin: Get to grips quickly with the best Java alternative

Arrow left icon
Profile Icon Samuel Profile Icon Bocutiu
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4 (7 Ratings)
Paperback Jan 2017 420 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Samuel Profile Icon Bocutiu
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4 (7 Ratings)
Paperback Jan 2017 420 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.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

Programming Kotlin

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 Kotlin
  • Use the REPL and write Kotlin scripts
  • Create a gradle project with Kotlin enabled
  • Create a Maven project with Kotlin enabled
  • Use IntelliJ to create a Kotlin project
  • Use Eclipse IDE to create a Kotlin project
  • Mix 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  kotlin@1.1-M04

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.jar
Exception in thread "main" java.lang.NoClassDefFoundError:  kotlin/jvm/internal/Intrinsics
at 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.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

Kotlin for scripting

Kotlin can also be run as a script. If bash or Perl is not for you, now you have an alternative.

Say you want to delete all the files older than N given days. The following code example does just that:

    import java.io.File 
    val purgeTime = System.currentTimeMillis() - args[1].toLong() * 24  * 60 * 60 * 1000 
    val folders = File(args[0]).listFiles { file -> file.isFile } 
    folders ?.filter { 
      file -> file.lastModified() < purgeTime } 
    ?.forEach { 
      file -> println("Deleting ${file.absolutePath}") 
      file.delete() 
    } 

Create a file named delete.kts with the preceding content. Please note the predefined variable args, which contains all the incoming parameters passed when it is invoked. You might wonder what is the ? character doing there. If you are familiar with the C# language and you know about nullable classes, you already have the answer. Even though you might not have come across it, I am sure you have a good idea of what it does. The character is called the safe call operator, and, as you will find out later in the book when the subject is discussed in greater length, it avoids the dreadful NullPointerException error.

The script takes two arguments: the target folder, and then the number of days threshold. For each file it finds in the target, it will check the last time it was modified; if it is less than the computed purge time, it will delete it. The preceding script has left out error handling; we leave this to the reader as an exercise.

Now the script is available, it can be invoked by running the following:

$ kotlinc -script delete.kts . 5

If you copy/create files in the current folder with a last modified timestamp older than five days, it will remove them.

Kotlin with Gradle

If you are familiar with the build tool landscape, you might be in one of three camps: Maven, Gradle, or SBT (more likely if you are a Scala dev). I am not going to go into the details, but we will present the basics of Gradle, the modern open source polyglot build automation system, and leave it up to the curious to find out more from http://gradle.org. Before we continue, please make sure you have it installed and available in your classpath in order to be accessible from the terminal. If you have SDKMAN, you can install it using this command:

$ sdk install gradle 3.0

The build system comes with some baked-in templates, although limited, and in its latest 3.0 version Kotlin is not yet included. Hopefully, this shortfall will be dealt with sooner rather than later. However, it takes very little to configure support for it. First, let's see how you can interrogate for the available templates:

$ gradle help --task :init

You should see the following being printed out on the terminal:

Options
--type  Set type of build to create.
Available values are:
basic
groovy-library
java-library
pom
scala-library

Let's go and use the Java template and create our project structure by executing this bash command:

$ gradle init --type java-library

This template will generate a bunch of files and folders; if you have been using Maven, you will see that this structure is similar:

Kotlin with Gradle

Project Folders layout

As it stands, the Gradle project is not ready for Kotlin. First, go ahead and delete Library.java and LibraryTest.java, and create a new folder named kotlin, a sibling of the java one. Then, using a text editor, open the build.gradle file. We need to add the plugin enabling the Gradle system to compile Kotlin code for us, so at the top of your file you have to add the following snippet:

    buildscript {
      ext.kotlin_version = '1.1-M04'

      repositories {
        maven { url "https://dl.bintray.com/kotlin/kotlin-dev" }
        mavenCentral()
      }
      dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
      }
    }

The preceding instructions tell Gradle to use the plugin for Kotlin, and set the dependency maven repository. Since Kotlin 1.1 is only at milestone 4, there is a specific repository to pick it from. See last entry in repositories. We are not done yet; we still need to enable the plugin. The template generated will already have an applied plugin: java. Replace it with the following:

    apply plugin: 'kotlin' 
    apply plugin: 'application' 
    mainClassName = 'com.programming.kotlin.chapter01.ProgramKt' 

Now Kotlin plugin support is enabled; you may have noticed that we have also added the application plugin, and set the class containing the program entry point. The reason for this is to allow the program to run directly, as we will see shortly.

We are not quite done. We still need to link to the Kotlin standard library. Replace the repositories and dependencies sections with the following:

    repositories {
      maven { url "https://dl.bintray.com/kotlin/kotlin-dev" }
      mavenCentral()
    } 
    dependencies { 
      compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 
      testCompile 'io.kotlintest:kotlintest:1.3.3' 
    } 

Now let's create the file named HelloWorld.Kt. This time, we will set a namespace and thus avoid having our class as part of the default one. If you are not yet familiar with the term, don't worry; it will be covered in the next chapter.

From the terminal, run the following:

$ mkdir -p src/main/kotlin/com/programming/kotlin/chapter01
$ 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 build and run the application:

$ gradle build
$ gradle run

Now we want to be able to run our program using java -jar [artefact]. Before we can do that, we need to adapt the build.gradle. First, we need to create a manifest file and set the main class; the JVM will look for the main function to start executing it:

    jar { 
      manifest { 
        attributes( 
          'Main-Class': 'com.programming.kotlin.chapter01.ProgramKt' 
        ) 
      } 
      from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } 
    } 

Furthermore, we also embed into the JAR the dependency for kotlin-stdlib, as well as kotlin-runtime. If we leave out these dependencies, we will need to add them to the classpath  when we run the application. Now you are ready to build and run the code.

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:

IntelliJ and Kotlin

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:

IntelliJ and Kotlin

Hello World! basic project

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

IntelliJ and Kotlin

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:

IntelliJ and Kotlin

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:

IntelliJ and Kotlin

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:

IntelliJ and Kotlin

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:

Eclipse and Kotlin

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:

Eclipse and Kotlin

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.

Mixing Kotlin and Java in a project

Using different languages within the same project is quite common; I came across projects where a mix of Java and Scala files formed the code base. Could we do the same with Kotlin? Absolutely. Let's work on the project created earlier, Kotlin with Gradle. You should see the following directory structure in your IntelliJ (the standard template for a Java/Kotlin project):

Mixing Kotlin and Java in a project

Project layout

You can place Java code within the java folder. Add a new package to the java folder with the same name as the one present in the kotlin folder: com.programming.kotlin.chapter01. Create a New | Java class named CarManufacturer.java and use this code for the purpose of the exercise:

    public class CarManufacturer { 
      private final String name; 
      public CarManufacturer(String name) { 
        this.name = name; 
      } 
      public String getName() { 
        return name; 
      } 
    } 

What if you want to add a Java class under the kotlin subfolder? Let's create a Student class similar to the previous one and provide a field name for simplicity:

    public class Student { 
      private final String name; 
      public Student(String name) { 
        this.name = name; 
      } 
      public String getName() { 
        return name; 
      } 
    } 

In the main function, let's instantiate our classes:

    fun main(args: Array<String>) { 
      println("Hellow World!") 
      val student = Student("Alexandra Miller") 
      println("Sudent name:${student.name}") 
      val carManufacturer = CarManufacturer("Mercedes") 
      println("Car manufacturer:${carManufacturer.name}") 
    } 

While the code compiles just fine, trying to run it will throw a runtime exception, saying that it can't find the Student class. We need to let the Java compiler look for code under the src/main/kotlin folder. In your gradle.build, add the following instruction:

    sourceSets { 
      main.java.srcDirs += 'src/main/kotlin' 
    } 

Now we can compile and run the program:

$gradle jar
$ java -jar build/libs/chapter01-1.0-SNAPSHOT.jar

As your Kotlin code gets bigger, compilation will slow down since it will have to go and recompile each file. There is a way to speed it up, though: by only compiling files changed between builds. The easiest way to enable this is to create a file called gradle.properties alongside build.gradle and add kotlin.incremental=true to it. While the first build will not be incremental, the following ones will be, and you should see your compilation time cut down quite a bit.

Maven is still, probably, the most used build system on the JVM. So let's see how we can achieve our goal of mixing Kotlin and Java code in Maven. Starting with IntelliJ, choose New | Project, pick Maven as the option, and look for kotlin-archetype-jvm from the list of archetypes. We already covered this, so it should be a lot easier the second time around. We now have a project.

From the project tree, you will notice that there is no java folder source code created. Go ahead and create src/main/java, followed by the namespace folder com.programming.kotlin (this will be a subfolder of the java one). You will notice that right-clicking on the java folder won't give you the option to create a package. The project is not yet configured to include Java code. But first, what makes Maven handle Kotlin code? If you open the pom.xml file and go to the plugins section, you will notice the kotlin plugin:

    <plugin> 
      <groupId>org.jetbrains.kotlin</groupId> 
      <artifactId>kotlin-maven-plugin</artifactId> 
      <version>${kotlin.version}</version> 
      <executions> 
        <execution> 
          <id>compile</id> 
          <phase>compile</phase> 
          <goals> 
            <goal>compile</goal> 
          </goals> 
        </execution> 
        <execution> 
          <id>test-compile</id> 
          <phase>test-compile</phase> 
          <goals> 
            <goal>test-compile</goal> 
          </goals> 
        </execution> 
      </executions> 
    </plugin> 

To add Java code to the mix, we need to set a new plugin that will be able to compile good old Java:

    <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-compiler-plugin</artifactId> 
      <version>3.5.1</version> 
      <executions> 
        <execution> 
          <id>default-compile</id> 
          <phase>none</phase> 
        </execution> 
        <execution> 
          <id>default-testCompile</id> 
          <phase>none</phase> 
        </execution> 
        <execution> 
          <id>java-compile</id> 
          <phase>compile</phase> 
          <goals> 
            <goal>compile</goal> 
          </goals> 
        </execution> 
        <execution> 
          <id>java-test-compile</id> 
          <phase>test-compile</phase> 
          <goals> 
            <goal>testCompile</goal> 
          </goals> 
        </execution> 
      </executions> 
    </plugin> 

The Kotlin compiler has to run before the Java compiler to get it all working, so we will need to amend the Kotlin plugin to do just that:

    <plugin> 
      <artifactId>kotlin-maven-plugin</artifactId> 
      <groupId>org.jetbrains.kotlin</groupId> 
      <version>${kotlin.version}</version> 
      <executions> 
        <execution> 
          <id>compile</id> 
          <goals> 
            <goal>compile</goal> 
          </goals> 
          <configuration> 
            <sourceDirs> 
              <sourceDir>${project.basedir}/src/main/kotlin</sourceDir> 
              <sourceDir>${project.basedir}/src/main/java</sourceDir> 
            </sourceDirs> 
          </configuration> 
        </execution> 
        <execution> 
          <id>test-compile</id> 
          <goals> 
            <goal>test-compile</goal> 
          </goals> 
          <configuration> 
            <sourceDirs> 
              <sourceDir>${project.basedir}/src/main/kotlin</sourceDir> 
              <sourceDir>${project.basedir}/src/main/java</sourceDir> 
            </sourceDirs> 
          </configuration> 
        </execution> 
      </executions> 
    </plugin> 

To be able to produce the executable JAR for the code we are about to write, we need yet another Maven plugin:

    <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-jar-plugin</artifactId> 
      <version>3.0.2</version> 
      <configuration> 
        <archive> 
          <manifest> 
            <addClasspath>true</addClasspath> 
            <mainClass>com.programming.kotlin.HelloKt</mainClass> 
          </manifest> 
        </archive> 
      </configuration> 
    </plugin> 

The preceding code will give you a JAR containing just your code; if you want to run it then you need the extra dependencies to the classpath:

    <plugin> 
      <groupId>org.apache.maven.plugins</groupId> 
      <artifactId>maven-assembly-plugin</artifactId> 
      <version>2.6</version> 
      <executions> 
        <execution> 
          <id>make-assembly</id> 
          <phase>package</phase> 
          <goals> <goal>single</goal> </goals> 
          <configuration> 
            <archive> 
              <manifest> 
                <mainClass>com.programming.kotlin.HelloKt</mainClass> 
              </manifest> 
            </archive> 
            <descriptorRefs> 
              <descriptorRef>jar-with-dependencies</descriptorRef> 
            </descriptorRefs> 
          </configuration> 
        </execution> 
      </executions> 
    </plugin> 

Now we are in a position to add the classes from the previous example (the CarManufacturer and Student classes) and change the main class to contain the following:

    val student = Student("Jenny Wood") 
    println("Student:${student.name}") 
    val carManufacturer = CarManufacturer("Honda") 
    println("Car manufacture:${carManufacturer.name}") 

This is not ready yet. While compiling will go well, trying to execute the JAR will yield an error at runtime about the Student class not being found. The Java compiler needs to know about the Java code sitting under the kotlin folder. For that, we bring in another plugin:

    <plugin> 
      <groupId>org.codehaus.mojo</groupId> 
      <artifactId>build-helper-maven-plugin</artifactId> 
      <executions> 
        <execution> 
          <phase>generate-sources</phase> 
          <goals><goal>add-source</goal></goals> 
          <configuration> 
            <sources> 
              <source>${project.basedir}/src/main/kotlin</source> 
            </sources> 
          </configuration> 
        </execution> 
      </executions> 
    </plugin> 

Finally, we are in a position to compile and run the code. Executing the commands in a terminal will end up printing three lines in the output:

$ mvn package
$ java -jar target/chapter01-maven-mix-1.0-SNAPSHOT-jar-with-dependencies.jar

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • ? Introduction to running, setup and tools of Kotlin code ? Writing structured and readable object-oriented code using new features alongside lambdas and higher order functions ? Writing unit tests and integrating Kotlin tests with Java code in a transitioning code base ? Guide through testing, concurrency and microservices ? Leveraging Kotlin?s extensions to the Java collections library ? Using destructuring expressions and finding out how to write your own ? Overview of null safety, type parameterization and Generics ? Setup of algebraic data types and learning when they should be used

Description

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.

Who is this book for?

Who is this book for? ? Java developers interested in learning about an alternative JVM language ? Server-side developers who want to learn the Kotlin language quickly ? Beginners interested in books on Kotlin for Android development

What you will learn

  • You?ll learn all the basics of the Kotlin language and be able to write Kotlin code to production. This book will have you comfortably using Java code alongside Kotlin, composing different services and building your own applications.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 18, 2017
Length: 420 pages
Edition : 1st
Language : English
ISBN-13 : 9781787126367
Vendor :
JetBrains
Category :
Languages :

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 : Jan 18, 2017
Length: 420 pages
Edition : 1st
Language : English
ISBN-13 : 9781787126367
Vendor :
JetBrains
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 146.97
Programming Kotlin
$48.99
Mastering Android Development with Kotlin
$48.99
Android Development with Kotlin
$48.99
Total $ 146.97 Stars icon
Banner background image

Table of Contents

13 Chapters
1. Getting Started with Kotlin Chevron down icon Chevron up icon
2. Kotlin Basics Chevron down icon Chevron up icon
3. Object-Oriented Programming in Kotlin Chevron down icon Chevron up icon
4. Functions in Kotlin Chevron down icon Chevron up icon
5. Higher Order Functions and Functional Programming Chevron down icon Chevron up icon
6. Properties Chevron down icon Chevron up icon
7. Null Safety, Reflection, and Annotations Chevron down icon Chevron up icon
8. Generics Chevron down icon Chevron up icon
9. Data Classes Chevron down icon Chevron up icon
10. Collections Chevron down icon Chevron up icon
11. Testing in Kotlin Chevron down icon Chevron up icon
12. Microservices with Kotlin Chevron down icon Chevron up icon
13. Concurrency Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4
(7 Ratings)
5 star 42.9%
4 star 0%
3 star 14.3%
2 star 42.9%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Zachary McDaniel Nov 15, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book for those that know Java but are new to kotlin!
Amazon Verified review Amazon
Amazon カスタマー Jun 04, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The contents are substantial.
Amazon Verified review Amazon
Amazon Customer Aug 27, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very very good book and a easy read.
Amazon Verified review Amazon
Mr Smith Jan 24, 2018
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
To be fair, this book might be great for an experienced Java programmer, but for basic beginning programming in Kotlin, forget it! I needed a good book as a teaching reference for beginners and this is not the book! I have looked through every Kotlin book on Amazon and not one author has a clue how to show and or teach beginner's basic Kotlin programming. Everyone's head is still buried in Java.
Amazon Verified review Amazon
B. Oakes Apr 04, 2019
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I bought this book as someone with java experience. I have to say however that the layout and wording of this book is not as expected. The book could be much better than it is. You can learn some kotlin by using it but it's not the best book.
Amazon Verified review Amazon
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.