How to create new Kotlin project by CLI?

Viewed 461

In dotnet I have a bunch of templates in dotnet new <template>, but how to do the same thing in kotlin?

Something like this

kotlin new kotlinNativeConsole

Which will create new native kotlin console application like single print("hello world!")

P.S(I know about intellij idea and it's templates, but I refuse to use because it simply not works on my machine and I always prefer command line)

1 Answers

Gradle has templates like that. You can download it here. This is in fact what IntelliJ IDEA uses to build Kotlin Native projects. I'll show you how you can use it on the command line, since you don't seem to like IntelliJ. To generate a new project, do

gradle init

And it will produce a new project wizard like this:

Starting a Gradle Daemon (subsequent builds will be faster)

Select type of project to generate:
  1: basic
  2: application
  3: library
  4: Gradle plugin
Enter selection (default: basic) [1..4] 2

Select implementation language:
  1: C++
  2: Groovy
  3: Java
  4: Kotlin
  5: Scala
  6: Swift
Enter selection (default: Java) [1..6] 4

Split functionality across multiple subprojects?:
  1: no - only one application project
  2: yes - application and library projects
Enter selection (default: no - only one application project) [1..2] 1

Select build script DSL:
  1: Groovy
  2: Kotlin
Enter selection (default: Kotlin) [1..2] 2

Project name (default: MyProject): 
Source package (default: MyProject): myproject

> Task :init
Get more help with your project: https://docs.gradle.org/7.2/samples/sample_building_kotlin_applications.html

BUILD SUCCESSFUL in 47s
2 actionable tasks: 2 executed

After selecting those options, you get a project structure like this:

enter image description here

App.kt looks like this:

/*
 * This Kotlin source file was generated by the Gradle 'init' task.
 */
package myproject

class App {
    val greeting: String
        get() {
            return "Hello World!"
        }
}

fun main() {
    println(App().greeting)
}

Note that this project template is a Kotlin/JVM project. For a Kotlin/Native project, you should follow the instructions here. To summarise, you should edit the build.gradle.kts file to include the Kotlin/Native plugin, then create a src/nativeMain/kotlin folder to put your main function there.

Related