Maven

If Maven is your build tool of choice, then setting up Kotlin will be just as easy.

In the same way as with Gradle, we first need to add a Kotlin plugin to a pom.xml file. You can do this by adding these lines to the plugins section:

<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>
</execution>
</executions>
</plugin>

We can define a Kotlin version at one place, inside the properties section:

<properties>
<kotlin.version>1.2.40</kotlin.version>
</properties>

In the same way as with Gradle, the Kotlin standard library needs to be added to dependencies.

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

If you are targeting JDK 8, you can replace kotlin-stdlib with kotlin-stdlib-jdk8 so you can have Kotlin extension functions that cover the latest APIs from JDK 8.

This should be enough if you plan on only writing Kotlin. If you are mixing Kotlin and Java inside a Maven project, a Kotlin compiler needs to run before a Java compiler. To instruct Maven to compile Kotlin first, the Kotlin plugin needs to be before the Maven compiler plugin.

Here's what the complete build section looks like:

<build>
<plugins>
<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>
</executions>
</plugin>
<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>java-compile</id>
<phase>compile</phase>
<goals> <goal>compile</goal> </goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

Finally, there are various Kotlin compiler options that can be set under the configuration section of a Kotlin plugin. Here's an example of how to instruct the compiler to produce a Java 1.8 compatible bytecode.

<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<jvmTarget>1.8</jvmTarget>
</configuration>
</plugin>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.71.21