Kotlin/JVM 入门
This tutorial demonstrates how to use IntelliJ IDEA for creating a console application.
To get started, first download and install the latest version of IntelliJ IDEA.
Create a project
- In IntelliJ IDEA, select File | New | Project.
- In the panel on the left, select New Project.
Name the new project and change its location if necessary.
Select the Create Git repository checkbox to place the new project under version control. You will be able to do it later at any time.
From the Language list, select Kotlin.
Select the IntelliJ build system. It's a native builder that doesn't require downloading additional artifacts.
If you want to create a more complex project that needs further configuration, select Maven or Gradle. For Gradle, choose a language for the build script: Kotlin or Groovy.
From the JDK list, select the JDK that you want to use in your project.
- If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
- If you don't have the necessary JDK on your computer, select Download JDK.
Enable the Add sample code option to create a file with a sample
"Hello World!"
application.You can also enable the Generate code with onboarding tips option to add some additional useful comments to your sample code.
Click Create.
If you chose the Gradle build system, you have in your project a build script file:
build.gradle(.kts)
. It includes thekotlin("jvm")
plugin and dependencies required for your console application. Make sure that you use the latest version of the plugin:plugins { kotlin("jvm") version "1.9.24" application }
Create an application
Open the
Main.kt
file insrc/main/kotlin
.
Thesrc
directory contains Kotlin source files and resources. TheMain.kt
file contains sample code that will printHello World!
.Modify the code so that it requests your name and says
Hello
to you alone, and not to the whole world:- Introduce a local variable
name
with the keywordval
. It will get its value from an input where you will enter your name –readln()
. - Use a string template by adding a dollar sign
$
before this variable name directly in the text output like this –$name
.
fun main() { println("What's your name?") val name = readln() println("Hello, $name!") }
- Introduce a local variable
Run the application
Now the application is ready to run. The easiest way to do this is to click the green Run icon in the gutter and select Run 'MainKt'.
You can see the result in the Run tool window.
Enter your name and accept the greetings from your application!
恭喜! 你现在运行了第一个 Kotlin 应用程序。
下一步做什么?
Once you've created this application, you can start to dive deeper into Kotlin syntax:
- Add sample code from Kotlin examples
- Install the JetBrains Academy plugin for IDEA and complete exercises from the Kotlin Koans course