Alex Craft
Alex Craft

Reputation: 15336

Kotlin compile and run from command line

How can I compile and run kotlin files? Without maven, gradle or kotlin-DSL-gradle, only command line options.

I have two kotlin files in the play folder

user.kt

data class User(val name: String)

play.kt

fun main() {
  val user = User("Jim")
  println("Hello ${user.name}")
}

I try running it as

kotlinc play.kt -cp . -include-runtime -d play.jar && java -jar play.jar
play.kt:2:14: error: unresolved reference: User
  val user = User("Jim")

But it fails to find User class, even though I set -cp ., how to make it work?

P.S.

Would it be possible to avoid building jar and use caching and incremental compilation, to make it faster?

Upvotes: 1

Views: 1108

Answers (1)

Alladywek
Alladywek

Reputation: 56

The problem is in your compile command, you specified only one file for compilation (play.kt), so the compiler sees that play.kt references to User.class and of course can not find this file in your classpath (-cp .), because you did not compile this file before, so you need to compile the whole folder play and skip -cp parameter.

try this: kotlinc play/ -include-runtime -d play.jar && java -jar play.jar

Regarding caching and incremental compilation - No, It is not the responsibility of Kotlin compiler (https://kotlinlang.org/docs/compiler-reference.html), you need to use build tools for this purposes.

Upvotes: 4

Related Questions