Skip to content

Latest commit

 

History

History

examples

Kotlin code examples

Kotlin project This repository gathers Kotlin code examples coming from various websites and books.
It also includes several build scripts (batch files, Gradle scripts) for experimenting with Kotlin on a Windows machine.

In this document we present the following Kotlin code examples (unless):

🔎 There exist three Kotlin compilers and some code examples are only valid with one of them:

  • The Kotlin/JVM compiler generates class/JAR files.
  • The Kotlin/JS compiler generates JavaScript code.
  • The Kotlin/Native compiler generates native codefor the supported targets [1].

We provide several ways to build/run the Kotlin code examples:

Build tool Build file(s) Parent file(s) Environment(s)
ant.bat build.xml   Any a)
cmd.exe build.bat
build.properties
cpath.bat b) Windows
sh.exe build.sh Cygwin/MSYS2/Unix
gradle.exe build.gradle c) common.gradle Any
gradle.exe build.gradle.kts d)   Any
mvn.cmd pom.xml pom.xml Any
make.exe Makefile Makefile.inc Any
a) Here "Any" means "tested on MS Windows / Cygwin / MSYS2 / Unix".
b) This utility batch file manages Maven dependencies and returns the associated Java class path (as environment variable).
c) Gradle build script written in Groovy DSL
d) Gradle build script written in Kotlin DSL
 

🔎 Command build.bat help displays the help message:

> build help
Usage: build { <option> | <subcommand> }
 
 Options:
   -debug      print commands executed by this script
   -native     generated native executable
   -timer      print total execution time
   -verbose    print progress messages
 
 Subcommands:
   clean       delete generated files
   compile     generate class files
   detekt      analyze Kotlin source files with Detekt
   doc         generate documentation
   help        print this help message
   lint        analyze Kotlin source files with KtLint
   run         execute the generated program
   test        execute unit tests

HelloWorld Example

Command build.bat clean run compiles source file HelloWorld.kt and executes the generated Java class file(s) 2:

> build clean run
Hello World!
 
> tree /a /f target\classes | findstr /v "^[A-Z]"
+---META-INF
|       main.kotlin_module
|
\---org
    \---example
        \---main
                HelloWorldKt.class

🔎 We observe the naming convention for generated class files: HelloWorldKt.class is generated for source file HelloWorld.kt.

Command build.bat -native clean run generates and executes the native executable for the default target 1:

> build -native clean run
Hello World!
 
> tree /a /f target | findstr /v "^[A-Z]"
    HelloWorld.exe
    kotlinc-native_opts.txt
    kotlinc-native_sources.txt

🔎 The pelook utility can help us getting more information about the native executable:

> pelook.exe -h target\HelloWorld.exe | head -7
loaded "target\HelloWorld.exe" / 478599 (0x74D87) bytes
signature/type:       PE64 EXE image for amd64
image checksum:       0x0007FD9A (OK)
machine:              0x8664 (amd64)
subsystem:            3 (Windows Console)
minimum os:           4.0 (Win95/NT4)
linkver:              2.32

JavaToKotlin Example (JVM only)

Either command build.bat clean run or command gradle.bat -q clean run compiles the source files IntBox.java, User.java and Main.kt and produces the following output:

> build clean run
name=<name> active=true
name=Bob active=true
three=3
 
> gradle -q clean run
name=<name> active=true
name=Bob active=true
three=3

See Kotlin reference documentation: Calling Java code from Kotlin.

KotlinToJava Example (JVM only)

Either command build.bat clean run or command gradle.bat -q clean run runJava compiles the source files JavaInteropt.java and JavaInterop.kt and produces the following output (Kotlin output first and then Java output):

> build clean run
[kt] this is a message: a message
[kt] another message: a message
 
[kt] call callback function
[java] Hello, hi!
[kt] call companion function
 
> gradle -q clean run runJava
[kt] this is a message: a message
[kt] another message: a message
 
[kt] call callback function
[java] Hello, hi!
[kt] call companion function

See Kotlin reference documentation: Calling Kotlin from Java.

LanguageFeatures Example

Either command build.bat clean run or command gradle.bat -q clean run compiles source file LanguageFeatures.kt and produces the following output:

> gradle -q clean run
int a: 2
penDown
forward 100.0
turn 90.0
forward 100.0
turn 90.0
forward 100.0
turn 90.0
forward 100.0
turn 90.0
penUp
250
John we welcome you!
200
-10
4
null

🔎 The list of error messages associated with the @Suppress annotation can be found in source file DefaultErrorMessages.java.

QuickSort Example

The project directory is organized as follows :

> tree /a /f . | findstr /v /b [A-Z]
|   00download.txt
|   build.bat
|   build.gradle
|   build.sh
|   build.xml
|   gradle.properties
|   Makefile
|   pom.xml
\---src
    +---main
    |   \---kotlin
    |           QuickSort.kt
    \---test
        \---kotlin
                QuickSortJUnitTest.kt

Command build.bat builds and runs the Java main program QuickSortKt.class :

> build clean run
Original Array: 64, 34, 25, 12, 22, 11, 90
Sorted Array: 11, 12, 22, 25, 34, 64, 90

Command make TOOLSET=native clean run builds and runs the native main program QuickSort.exe :

> make TOOLSET=native clean run
"/usr/bin/rm.exe" -rf "target"
## Check Maven dependencies on https://repo1.maven.org/maven2
[ -d "target/classes" ] || "/usr/bin/mkdir.exe" -p "target/classes"
"C:/opt/kotlinc-1.9.23/bin/kotlinc.bat" -language-version 1.7 -d target/classes src/main/kotlin/QuickSort.kt
"C:/opt/jdk-temurin-17.0.11_9/bin/jar.exe" cf target/QuickSort.jar -C target/classes .
"C:/opt/kotlinc-1.9.23/bin/kotlin.bat" -cp target/QuickSort.jar QuickSortKt
Original Array: 64, 34, 25, 12, 22, 11, 90
Sorted Array: 11, 12, 22, 25, 34, 64, 90

Reflection Example (JVM only)

Command build.bat -timer clean run compiles source file Reflection.kt and produces the following output:

> build -timer clean run
Source code:
    data class Person(
        val name: String,
        var age: Int
    )

Methods:
    fun component1: class java.lang.String
    fun component2: int
    fun copy: class Person
    fun copy$default: class Person
    fun equals: boolean
    fun getAge: int
    fun getName: class java.lang.String
    fun hashCode: int
    fun setAge: void
    fun toString: class java.lang.String

Members:
    var age: kotlin.Int
    val name: kotlin.String
Elapsed time: 00:00:06

Alternatively command gradle.bat -q clean run (build script build.gradle and property file gradle.properties) produces the same result:

> gradle clean run

> Task :run
Source code:
    data class Person(
        val name: String,
        var age: Int
    )

Methods:
    fun component1: class java.lang.String
    fun component2: int
    fun copy: class Person
    fun copy$default: class Person
    fun equals: boolean
    fun getAge: int
    fun getName: class java.lang.String
    fun hashCode: int
    fun setAge: void
    fun toString: class java.lang.String

Members:
    var age: kotlin.Int
    val name: kotlin.String

BUILD SUCCESSFUL in 3s
3 actionable tasks: 3 executed

🔎 Execution time for command build.bat is always 6 seconds while with command gradle.bat that time goes down from 15 seconds to 3 seconds once the Gradle daemon is running (see command gradle --status).

SelectionSort Example

The project directory is organized as follows :

> tree /a /f . | findstr /v /b [A-Z]
|   00download.txt
|   build.bat
|   build.gradle
|   build.sh
|   build.xml
|   gradle.properties
|   Makefile
|   pom.xml
\---src
    +---main
    |   \---kotlin
    |           SelectionSort.kt
    \---test
        \---kotlin
                SelectionSortJUnitTest.kt

Command build.bat builds and runs the Java main program SelectionSortKt.class :

> build clean run
Original Array: 64, 34, 25, 12, 22, 11, 90
Sorted Array: 11, 12, 22, 25, 34, 64, 90

Footnotes

[1] Available targets

Command kotlinc-native -list-targets displays the list of available targets:
> kotlinc-native -version
info: kotlinc-native 1.9.20 (JRE 11.0.21+9)
Kotlin/Native: 1.9.20
 
> kotlinc-native -list-targets
linux_x64:                              linux
linux_arm32_hfp:                        raspberrypi
linux_arm64:
linux_mips32:
linux_mipsel32:
mingw_x86:
mingw_x64:                    (default) mingw
android_x86:
android_x64:
android_arm32:
android_arm64:
wasm32:

[2] Kotlin compiler option -d

The Kotlin/JVM compiler generates a single Java archive file if the -d option argument ends with .jar (in our case target\HelloWorld.jar).
> kotlinc -d target\HelloWorld.jar src\HelloWorld.kt
> dir target | findstr HelloWorld.jar
02.11.2019  16:45             1 164 HelloWorld.jar
 
> jar tf target\HelloWorld.jar
META-INF/MANIFEST.MF
HelloWorldKt.class
META-INF/main.kotlin_module

[3] Execution on JVM

On the JVM platform a Kotlin program can be executed in several ways depending on two parameters: - We run command kotlin.bat or command java.exe. - We generated either class files or a single JAR file for our HelloWorld program.
CommandClass/JAR fileSession example
kotlin.batHelloWorldKt> kotlin -cp target\classes HelloWorldKt
Hello World!
 HelloWorld.jar> kotlin -J-Xbootclasspath/a:%CPATH% -jar target\HelloWorld.jar
Hello World!
java.exeHelloWorldKt> java -cp %CPATH%;target\classes HelloWorldKt
Hello World!
 HelloWorld.jar> java -Xbootclasspath/a:%CPATH% -jar target\HelloWorld.jar
Hello World!
(1) CPATH=c:\opt\kotlinc-1.4.32\lib\kotlin-stdlib.jar
The command line is shorter if the Kotlin runtime is included in archive file HelloWorld.jar (option -include-runtime):
> kotlinc -include-runtime -d target\HelloWorld.jar src\HelloWorld.kt
> dir target | findstr HelloWorld.jar
02.11.2019  16:40         1 309 824 HelloWorld.jar
 
> jar tf target\HelloWorld.jar
META-INF/MANIFEST.MF
HelloWorldKt.class
META-INF/main.kotlin_module
kotlin/collections/ArraysUtilJVM.class
kotlin/jvm/internal/CallableReference$NoReceiver.class
kotlin/jvm/internal/CallableReference.class
[..]
kotlin/coroutines/EmptyCoroutineContext.class
kotlin/coroutines/intrinsics/CoroutineSingletons.class
 
> java -jar target\HelloWorld.jar
Hello World!

mics/May 2024