How-To – Use Gradle inside Visual Studio Code to build your Kotlin/Native applications (on a Mac)

In my last How-To – Build and run a Kotlin/Native application with Visual Studio Code on macOS I showed you how to setup, build, and run your first Kotlin/Native application using the barebone Kotlin/Native compiler inside Visual Studio Code (VSC). With Gradle, all the previous steps can be automated in just a couple of easy steps. Moreover, with Gradle, it becomes also feasible to handle the development of even large applications.

Installing Gradle (with Homebrew)

Because you are reading this How-To, I assume you know what Gradle is? In case you don’t, let’s stay very brief about it: Gradle is a tool that manages all the dependencies your project relies on, it configures all tools for the build process, it builds your project and: it has to be installed!

In fact, having Gradle in place, you don’t even need to follow my last tutorial (except for the short VSC part). Gradle will take care of downloading, installing and running the Kotlin/Native compiler! Nice, isn’t it?

Do you want to know more? Check out the official Gradle site here: https://gradle.org

To install Gradle you have at least two options:

  1. Follow the official guide for installation at https://gradle.org/install/
  2. Install Gradle via the fabulous package manager for Mac called Homebrewhttps://brew.sh

If you choose to use Homebrew (and I sincerely encourage you to do so), just fire up a terminal window (or use the one that you have opened for installing Homebrew) and run the two commands:

brew update
brew install gradle

The first command will update all the package definitions of the Homebrew repositories. This way you will have all the up-to-date tools available. The second command installs and registers Gradle.
Check if Gradle is working correctly by executing the following command:

gradle -version

Gradle -version output

To get the most out of Gradle inside VSC make sure you have the Gradle Language Support plugin installed: https://marketplace.visualstudio.com/items?itemName=naco-siren.gradle-languageGradle Language Support Plugin

Finished!

At least for the Gradle installation, now let’s move on to VSC and the first Gradle based Kotlin/Native project.

Setting up a new minimal Kotlin/Native project in VSC

Because we are using Gradle now, it is not necessary anymore to change the executor file extension mapping settings as I showed you in my previous How-To. Gradle takes care of the file discovery and compilation out of the box as long as you follow some file and folder structuring rules. If not, you will have to do some advanced Gradle configuration, which is not the focus of this tutorial.

  1. Fire up VSC and (for this How-To) close any workspaces, folders, and files in VSC. Start with a clean desk.
  2. Open an empty folder where you want to store this little example project.
  3. Create a new File in this directory called build.gradle
    If you have the plugin vscode-icons installed (as explained), you will see a nice pictogram in front of the filename. Gradle File Icon
  4. Insert the following minimal Gradle configuration into this file (explanation will follow further down):
    buildscript {
        repositories {
            mavenCentral()
            maven {
                url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies"
            }
        }
        dependencies {
            classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:+"
        }
    }
    
    apply plugin: 'konan'
    
    konan.targets = ['macbook']
    
    konanArtifacts {
        program('hello')
    }
    
  5. Next, create the necessary folder structure which enables Gradle to find your main source file. Starting with version 1.21 of VSC, you can simply hit the New Folder New Folder Button button in your Explorer-view on the left-hand side and type in src/main/kotlin inside the appearing new folder. VSC will automatically create all subfolders, i.e., src, main and kotlin.
  6. Create the main source file inside the kotlin subfolder, called (in this How-To at least) hello.kt
  7. Insert the following code snippet inside the hello.kt file:
    fun main(args: Array<String>) {
        println("Hello Gradle!")
    }
    
  8. Save the file!
  9. If everything is done correctly, your Explorer-view should be similar to the following screenshot:Kotlin/Native - VSC Explorer-view for Gradle app
  10. To build the application open VSC’s build in Terminal-view (either via View → Integrated Terminal, or via a right-click on the top-most folder and selecting Open in Terminal)How-To - open a terminal in VSC
  11. Execute the command
    gradle build
  12. Be patient; the first run takes very long due to all the dependencies that have to be loaded (like the Kotlin/Native compiler and dependencies if not already installed!).
  13. You should end up with a newly created folder structure.
    While the .gradle folder contains all the meta information of your build environment, the build/konan/bin/macbook folder contains your built executable file called hello.kexe
    Kotlin/Native - VSC Explorer-view for Gradle app after the build
  14. To run your new application, you can, e.g., execute the following command via the terminal while still in the top-most folder of your project/workspace.
    ./build/konan/bin/macbook/hello.kexe
  15. Finished.Application output

Now you can read you through the extensive Gradle documentation and create complex applications with a ton of internal and external dependencies.

 

A brief explanation of the minimal gradle.build file

Nevertheless, let us retake a look at our minimal build configuration to understand the basics.

buildscript {
    repositories {
        mavenCentral()
        maven {
            url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies"
        }
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:+"
    }
}

apply plugin: 'konan'

konan.targets = ['macbook']

konanArtifacts {
    program('hello')
}

Lets split it up:

buildscript {
    repositories {
        mavenCentral()
        maven {
            url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies"
        }
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:+"
    }
}

This section resolves all dependencies needed for the build tool to build Kotlin/Native apps on your Mac. It loads all required libraries and builds them, if necessary, in-place. Therefore the first run takes a lot longer.

apply plugin: 'konan'

This line applies the Gradle-plugin needed for running the Kotlin/Native tools from the Gradle toolchain.

konan.targets = ['macbook']

You can instruct the Kotlin/Native tools and therefore Gradle to build executables for several platforms like Windows, Linux, iOS or Android. In our case, we want a macOS file, which is labeled with the macbook tag. Not the best naming choice, but maybe subject to be changed in future Kotlin/Native releases.

konanArtifacts {
    program('hello')
}

Finally, the artifacts section tells Gradle which output (Artefact) to produce. The string ‚hello‘ is the output file’s name. You can name your .kexe file however you like. Gradle does not care in this simple example how the source-file is called. The simple reason is, that whenever you provide only one entry point (aka. main-function) in your project, the file containing it will be used as starting point for the compilation. More complex projects also require more complex Gradle configurations. Android Studio for example, which also uses Gradle heavily for Android development, does most of the Gradle configuration for you. Maybe also VSC will be that smart in the future. For this time being, you have to do all the work yourself with Kotlin/Native and VSC. But it is nice to see that the tools are running that easily already in this early stage of development of Kotlin/Native.

To-Do: Integrating the build, run and debug tasks into VSC

While in this How-To I showed you how to use Gradle for Kotlin/Native on a Mac, the dependency on Visual Studio Code is still quite low. At this time, we use VSC solely for writing code and the Gradle settings. We also have some help on hand, like syntax highlighting and some code completion. However, you can have this functionality in merely every sophisticated code editor. Using the command line interpreter (aka. terminal window) is also nothing VSC related.

The actual benefits from a fully integrated development environment (IDE) start when you can build, run and debug code from within the IDE. I will try to cover those points in one of my future posts.


If you like what I do and want to support me, please consider buying your next tech over one of the following partner links. No drawbacks for you, but some free coffee for me. ☕


Stay productive,
Martin

2 Gedanken zu “How-To – Use Gradle inside Visual Studio Code to build your Kotlin/Native applications (on a Mac)

  1. Mitch

    Thanks for this. I’m using Windows, but I only needed to changed konan.targets to ‚mingw‘ and it worked perfectly. It would be nice if debugging worked in VS Code, as I’m not a big fan of IntelliJ Idea (it’s great, but I prefer something lightweight). The situation was similar with Go and VS Code, but building and running/debugging Go works great now. I hope the case will be the same for Kotlin eventually.

    Antworten
    1. Martin Majewski Artikelautor

      Great! I’m glad I could help.

      As I play with Kotlin/Native and VSC only in my spare time, it could take some time, or it could be like tomorrow until I will hopefully figure out the debugging stuff. However, as soon as I do, I will post a new How-To here!

      So stay tuned and productive! 😉

      Best wishes,
      Martin

      Antworten

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.