Our first Kotlin program

In order to start writing programs for the Lego EV3 Mindstorms using Kotlin, we need the following:

  1. At least one Lego EV3 Mindstorms kit (31313)
  2. Install LeJOS in your brick. See the official wiki page.
  3. Download and install IntelliJ IDEA (Community or Ultimate Edition)
  4. Install LeJOS Plugin for Lego EV3 Mindstorms. (Get version 1.3 which adds Kotlin Support)

Creating Kotlin project

1. Open IntelliJ Idea and select: File > New > Project

2. On the popup, select JDK 7 (LeJOS libraries only work with this version) , Kotlin/JVM, and click Next.

3. Once you finish creating your project, look at the External Libraries section:

Notice that you need to have KotlinJavaRuntime and a bunch of LeJOS libraries that are needed to start writing programs for the Lego EV3 Mindstorms brick.

4. Let’s create a package named hellokotlin¬†and one Kotlin file named Main

5. Write a simple Hello Kotlin! in the main function:

package hellokotlin

import lejos.hardware.BrickFinder

fun main(args: Array<String>) {

    val LCD = BrickFinder.getLocal().textLCD
    LCD.clear()
    LCD.drawString("Hello Kotlin!", 3, 3)

    BrickFinder.getLocal().keys.waitForAnyPress()
}

6. Now let’s create a running configuration for LeJOS. Go to Run > Edit Configurations

7. Connect your Lego brick and run it. We should get this on the brick.

8. And that’s it. Now we can use the amazing Kotlin features to build Lego robots. Press any key on your brick to exit the program.

Notes:
Source code

Miguel

3 comments

  1. Hi i trying repeat this example but got error, when run play button.

    java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
    at hellokotlin.MainKt.main(Main.kt)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at lejos.internal.ev3.EV3Wrapper.invokeClass(EV3Wrapper.java:62)
    at lejos.internal.ev3.EV3Wrapper.main(EV3Wrapper.java:46)
    Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    … 7 more

    1. Hi, make sure you are using jdk 7. That error typically means you are compiling your code with a different jdk, probably 8.

Leave a Reply

Your email address will not be published. Required fields are marked *