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

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, run the following command in an empty directory:

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

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 src/test/java/com/programming/kotlin, and create the src/main/kotlin directory (the subdirectory structure matches the namespace name), as shown in the following code:

$ 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:

<properties> 
<kotlin.version>1.3.31</kotlin.version>
<kotlin.test.version>3.3.2</kotlin.test.version>
</properties>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<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 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 where 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-runner-junit5</artifactId> 
          <version>${kotlin.test.version}</version> 
          <scope>test</scope> 
        </dependency> 
      </dependencies>

It is now time to add the Hello World! code; this step is similar to the one we took earlier when we discussed Gradle, as you can see from the following code:

$ 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 using the following code:

$ 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, as follows:

$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 result JAR and produce what is called a fat jar. For that, however, another plugin needs to be added, as shown in the following code:

    <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, as follows:

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

The result of executing this command is to launch the JAR and execute the program.