Search code examples
kotlinkotlin-multiplatform

Setting Up a Multiplatform Project


considering Kotlin 1.2 introduced kotlin-platform-common I'm trying to build my first common .class file, so I did the below:

main.kt:

package hello

fun main() {
    println("kotlin!")
} 

gradle.build:

group 'h'
version 'prn'

buildscript {
    ext.kotlin_version = '1.2.0'

    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

apply plugin: 'kotlin-platform-common'

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-common:$kotlin_version"
}

sourceSets {
    main.kotlin.srcDirs += 'src/kotlin'
    main.resources.srcDirs += 'src/resources'
}

jar {
    manifest {
        attributes 'Main-Class': 'hello.MainKt'
    }
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}

Then I run gradle build

Q1- I coud not find any .class file generated? how to get it generated and where should I find it?

Q2- I got a .jar file generated, but once I tried to run it, I got an error:

Error: Could not find or load main class hello.MainKt

I tried to run it using the below 2 option, but got the same error for bot:

Option 1:

kotlin -cp <filename>.jar hello.MainKt

Option 2:

java -jar <filename>.jar

Project structure, and errors are as in this pic below:

enter image description here


Solution

  • With Kotlin 1.2, common modules don't generate binaries (like .class files), only metadata files. This is true even if you don't use the expect keyword anywhere.

    So you have to create another module which includes something like this:

    apply plugin: 'kotlin-platform-jvm'
    

    The JVM modules will also need an expectedBy entry in dependencies for your common module. Plus you'll probably want a corresponding JS module of course.

    It's probably best to let IntelliJ create the whole multiplatform project for you and then edit the Gradle files to suit, but this page lists the manual steps: https://kotlinlang.org/docs/reference/multiplatform.html#setting-up-a-multiplatform-project