Kotlin Basic Syntax
Starting from package declarations and program entry points, this article gradually introduces the most basic and commonly used syntax elements of Kotlin.
These rules appear in almost every tutorial that follows, so they are worth understanding first.
Package Declarations and import
A package declaration is written at the very top of a source file to group code and avoid naming conflicts.
The package name does not have to match the directory structure exactly, but keeping them consistent is common practice and is almost always followed in projects.
Example
// File path: com/runoob/Util.kt
package
com.runoob
// The package declaration must be on the first line of the file (except comments)
import
kotlin.math.PI
// Import a single declaration
import
kotlin.math.sqrt
// Import one per line
fun circleArea
(
r
:
Double
)
:
Double
=
PI
r
r
fun main
(
)
{
println
(
"Circle area with radius 2: ${sqrt(circleArea(2.0) / PI)}"
)
}
The output is as follows.
半径 2 的圆面积:2.0
If names conflict, you can use as to give an imported declaration an alias.
Example
// File path: Alias.kt
import
kotlin.math.PI
as PI_VALUE
// Give an alias to avoid conflicts with symbols of the same name
import
java.util.Date
as JavaDate
// Distinguish two classes with the same name from different sources
fun main
(
)
{
println
(
"Pi is approximately $PI_VALUE"
)
println
(
JavaDate
::
class
.
java
.
simpleName
)
}
圆周率约等于 3.141592653589793
Date
Using * you can import all declarations from a package at once.
Example
// File path: Wildcard.kt
import
kotlin.math.*
// Import all declarations under kotlin.math
fun main
(
)
{
println
(
max
(
3
,
7
)
)
// No need to write kotlin.math.max
println
(
abs
(
5
)
)
}
7
5
Default Imports
To reduce boilerplate, Kotlin imports a set of common packages by default, so you don't need to import them manually.
| Default Import | Contents |
|---|---|
| kotlin.* | Standard library core, such as Int, String, println, arrayOf |
| kotlin.annotation.* | Annotation related, such as Target, Retention |
| kotlin.collections.* | Collection types, such as List, Set, Map |
| kotlin.comparisons.* | Comparator utilities, such as compareBy, naturalOrder |
| kotlin.io.* | Input/output, such as readln, readLine |
| kotlin.ranges.* | Ranges, such as IntRange, until |
| kotlin.sequences.* | Sequences, such as sequenceOf, generateSequence |
| kotlin.text.* | Strings and regex, such as Regex, StringBuilder |
| java.lang.* | Additional default imports on the JVM platform, only valid for Kotlin/JVM |
| kotlin.jvm.* | JVM platform utilities, only valid for Kotlin/JVM |
The last two lines are specific to the JVM backend and do not exist when compiling to JS or Native.
So println, listOf, and Regex need no import.
Program Entry Point main
The entry point of a Kotlin program is the main function, which must be written at the top level, that is, not belonging to any class.
The simplest form takes no parameters and is equivalent to Java's public static void main(String[] args).
Example
// File path: Main.kt
fun main
(
)
{
println
(
"Hello, Runoob!"
)
}
Hello, Runoob!
When you need to read command-line arguments, use the form with parameters, whose type is an array of strings.
Example
// File path: Args.kt
fun main
(
args
:
Array
<
String
)
{
println
("Number of arguments: ${args.size}"
)
// 0 when no arguments are passed
val name
=
args.
firstOrNull
(
)
?:
"Runoob"
// Give a default value when there are no parameters
println
(
"Welcome, $name"
)
}
Run kotlinc -script or run directly with arguments, and the output is as follows.
$ kotlinc Args.kt -include-runtime -d args.jar
$ java -jar args.jar Runoob Tutorial
参数个数:1
欢迎访问 Runoob Tutorial
Since Kotlin 1.3, suspend functions are also supported as an entry point, written as suspend fun main().
It runs in a coroutine and can directly call other suspend functions, commonly used in command-line tools and coroutine examples.
Example
// File path: SuspendMain.kt
// suspend fun main is supported since Kotlin 1.3; the entry point itself is a suspend function
suspend fun fetchSite
(
)
:
String
{
return
"www.runoob.com"
// In real scenarios this might be a network request
}
suspend fun main
(
)
{
println
(
"Fetching site information..."
)
println
(
"Site address: "
fetchSite
(
)
)
}
正在获取站点信息…
站点地址:www.runoob.com
Tip:Can a file contain both a normal main and suspend main and a suspend main? No, there can be only one JVM entry point; writing both causes a compilation error.
Variables and Constants
Kotlin uses val to declare immutable variables and var to declare mutable variables.
val is equivalent to a Java final variable; once assigned, it cannot point to another object.
Example
// File path: Variables.kt
fun main
(
)
{
val siteName
=
"Runoob Tutorial"
// val: cannot be reassigned
var count
=
1
// var: can be reassigned
count
=
count
1
// Valid, because count is a var
println
(
"$siteName visit number $count"
)
// siteName = "RUNOOB" // Uncommenting causes a compile error: Val cannot be reassigned
}
Runoob Tutorial 第 2 次访问
The official style guide recommends preferring val, and using var only when modification is truly needed.
This reduces state changes, making the code easier to reason about and test.
Type Inference
When declaring a variable you can omit the type; the compiler infers it automatically from the initial value.
Example
// File path: Inference.kt
fun main
(
)
{
val name
=
"Runoob"
// Inferred as String
val age
=
25
// Inferred as Int
val price
=
9.9
// Inferred as Double
val isOpen
=
true
// Inferred as Boolean
println
(
"$name $age $price $isOpen"
)
println
(
name
::
class
.
simpleName
)
// Print the runtime type name
}
Runoob 25 9.9 true
String
You can also write the type explicitly; it is required when declaration and assignment are separate.
Example
// File path: ExplicitType.kt
fun main
(
)
{
val siteName
:
String
=
"Runoob Tutorial"
// Explicitly specify the type
var age
:
Int
// Declare without assigning; the type is required here
age
=
25
// Assign later
println
(
"$siteName,age = $age"
)
}
Runoob Tutorial,age = 25
Note:When you declare without assigning, the compiler cannot infer the type, so it must be written explicitly. var allows declaring first and assigning later, while val must be assigned at the point of declaration.
Notes
Kotlin comments come in single-line and block forms, written the same way as in C-family languages.
A single-line comment starts with two slashes, while a block comment is wrapped in a pair of slash-asterisks.
Example
// File path: Comments.kt
// This is a single-line comment; everything from // to the end of the line is ignored
/*
* This is a block comment
* It can span multiple lines
*/
fun main
(
)
{
println
(
"RUNOOB"
)
// End-of-line comment
}
The result is shown below; comments produce no output.
RUNOOB
Unlike Java, Kotlin block comments can be nested.
This is very useful when commenting out a block of code that already contains block comments.
Example
// File path: NestedComment.kt
/* Outer comment begins
/* Inner comment; Kotlin allows nested block comments */
Outer comment continues
It only truly ends here
*/
fun main
(
)
{
println
(
"Nested comment test passed"
)
}
注释嵌套测试通过
Java block comments cannot be nested, so the same code would cause a compile error in Java.
String templates
String templates are one of Kotlin's most beloved features; you can reference variables directly inside strings.
Just use $ followed by a variable name; wrap simple expressions in ${}.
Example
// File path: Template.kt
fun main
(
)
{
val siteName
=
"Runoob Tutorial"
val url
=
"www.runoob.com"
println
(
"Welcome to $siteName"
)
// Reference a variable directly
println
(
"URL: ${url.uppercase()}"
)
// Expressions can go inside the braces
println
(
"Name length: ${siteName.length}"
)
// Access a property
println
(
"Next year will be the ${2026 - 2010}th anniversary"
)
// Arithmetic expression
}
欢迎访问 Runoob Tutorial
网址:WWW.RUNOOB.COM
名称长度:4
明年将是 16 周年
If $ is not followed by a valid identifier, no escaping is needed.
To output a dollar sign itself inside a string, just escape it with a backslash.
Example
// File path: Dollar.kt
fun main
(
)
{
println
(
"The price is $9.9"
)
// Escape the dollar sign
println
(
"5$ can buy 1 tutorial"
)
// The $ here is also treated as a normal character
}
价格是 $9.9
5$ 可以买到 1 份教程
Semicolons are optional
Kotlin does not require a semicolon at the end of a statement; a line break itself marks the end.
You can separate statements with semicolons on a single line, but the official style guide does not recommend it.
Example
// File path: Semicolon.kt
fun main
(
)
{
val a
=
1
// Recommended: one statement per line, no semicolons
val b
=
2
val c
=
3
;
val d
=
4
// Legal but not recommended: multiple statements on one line with semicolons
println
(
"${a + b} ${c + d}"
)
}
3 7
Pay attention to line breaks; Kotlin splits statements by line breaks, and some multi-line expressions can be misinterpreted.
Example
// File path: LineBreak.kt
fun main
(
)
{
val x
=
1
2
// With the operator at the end of the line, the expression can span lines
val y
=
10
3
// This is treated as two statements: val y = 10 and -3
println
(
"x = $x, y = $y"
)
// y is still 10
}
x = 3, y = 10
Put the minus sign at the end of the previous line to get the result y = 7.
A First Look at Null Safety
Kotlin encodes the possibility of null into the type system, which is one of its biggest differences from Java.
Adding a question mark after a type makes it nullable; without it, the type is definitely non-null.
Example
// File path: NullSafety.kt
fun main
(
)
{
val notNull
:
String
=
"Runoob"
// Non-null type; cannot be assigned null
val maybeNull
:
String
?
=
null
// Nullable type; can be assigned null
println
(
notNull.
length
)
// Non-null types allow direct member access
// println(maybeNull.length) // Compile error: Only safe call allowed
println
(
maybeNull
?
.
length
)
// Safe call; result is null
println
(
maybeNull
?
.
length
?:
0
)
// Elvis operator; provides a default value when null
}
6
null
0
Nullable types cannot call members directly; you must handle them with ?. or ?:.
It is this rule that eliminates the vast majority of null pointer exceptions at compile time in Kotlin.
Tip:Null safety involves ?.、?:、!!、lateinit, platform types and other topics; this article only offers a preliminary understanding. For the full content, see Chapter 27, "Kotlin Null Safety》。
Common questions
The following pitfalls occur most frequently at the beginner stage.
Val cannot be reassigned
If you try to reassign a val variable, switch to var, or use a different variable name.
Unresolved reference
A typo, or forgetting to import the corresponding package. In IDEA, press Alt+Enter to auto-complete the import.
Error in the top-level main function
Make sure main is written at the top level of the file rather than inside a class, and the parameter type must be Array
An invalid character follows $ in a string template
Change it to ${'$'} or escape it with a backslash.