Kotlin from the ground up, Part 1 - setup, compile, jar package

0 33
Avatar for marley
Written by
4 years ago
  1. Get the command line compiler

    Visit https://github.com/JetBrains/kotlin/releases/latest, scroll down to the bottom and download kotlin-compiler-x.y.z.zip

  2. Set up environment

    First, install the JDK withJAVA_HOME pointed to its folder and the bin directory under it added to your PATH variable.

    Then unzip kotlin-compiler-x.y.z.zip into a directory of your choice (e.g. d:\kotlincor /usr/local/kotlinc) and add d:\kotlinc\bin or /usr/local/kotlinc/bin to your path.


  3. Write a test program, save it

    fun isEven(k:Int): Boolean =   
      k % 2 == 0
    
    fun main() {  
      println( "${ listOf(1,2,8,8,10,3).filter(::isEven) }" )
    }

    and compile it

    > kotlinc iseven.kt


    This generates IsevenKt.class and you can invoke it like below so needed classes in Kotlin's standard library can be found:

    > java -cp "d:\kotlinc\lib\kotlin-stdlib.jar;." IsevenKt
    [2, 8, 8, 10]

    e.g. the classpath (-cp) should include the Kotlin Standard Library jar file and any classes in the current directory.


  4. Alternatively, by using -include-runtime, you can create a standalone single-file jar that you can run from any environment with a java runtime installed:

    >kotlinc -include-runtime iseven.kt -d iseven.jar
    
    >java -jar iseven.jar
    [2, 8, 8, 10]


Postscript: You will eventually find yourself using an IDE like IntelliJ and build system beasts like Gradle/Maven/etc. but doing it manually like above & figuring out how to fix the errors and warnings that crop up is very educational and will deepen your knowledge wrt troubleshooting, library/package structure, etc.

You are welcome to post such issues in the comments below and see if I and others can help you troubleshoot. As we are on read.cash, it's also an opportunity to tip and be tipped Bitcoin Cash (BCH) not just on the article but on comments as well!

It is very helpful to know which packages are imported by default as mentioned in https://kotlinlang.org/docs/reference/packages.html:

Now let's fire up the Kotlin REPL and do some cool stuff in Part 2!

5
$ 1.00
$ 1.00 from @Read.Cash
Avatar for marley
Written by
4 years ago

Comments