Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Programming Kotlin

You're reading from   Programming Kotlin Get to grips quickly with the best Java alternative

Arrow left icon
Product type Paperback
Published in Jan 2017
Publisher Packt
ISBN-13 9781787126367
Length 420 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Stefan Bocutiu Stefan Bocutiu
Author Profile Icon Stefan Bocutiu
Stefan Bocutiu
Stephen Samuel Stephen Samuel
Author Profile Icon Stephen Samuel
Stephen Samuel
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

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

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
You have been reading a chapter from
Programming Kotlin
Published in: Jan 2017
Publisher: Packt
ISBN-13: 9781787126367
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime