Kotlin Basic Syntax
Kotlin files are suffixed with .kt
.
Package Declaration
The beginning of a code file is generally a package declaration:
package com.tutorialpro.main
import java.util.*
fun test() {}
class tutorialpro {}
Kotlin source files do not require matching directories and packages; source files can be placed in any file directory.
In the above example, the full name of test()
is com.tutorialpro.main.test
, and the full name of tutorialpro
is com.tutorialpro.main.tutorialpro
.
If no package is specified, it defaults to the default
package.
Default Imports
Several packages are imported by default into each Kotlin file:
kotlin.*
kotlin.annotation.*
kotlin.collections.*
kotlin.comparisons.*
kotlin.io.*
kotlin.ranges.*
kotlin.sequences.*
kotlin.text.*
Function Definition
Function definitions use the keyword fun
, with parameter format as: parameter : type
fun sum(a: Int, b: Int): Int { // Int parameter, return value Int
return a + b
}
Expression as the function body, return type automatically inferred:
fun sum(a: Int, b: Int) = a + b
public fun sum(a: Int, b: Int): Int = a + b // public method must explicitly state the return type
Function with no return value (similar to void in Java):
fun printSum(a: Int, b: Int): Unit {
print(a + b)
}
// If returning Unit type, it can be omitted (this is also true for public methods):
public fun printSum(a: Int, b: Int) {
print(a + b)
}
Variable-length Parameter Functions
Variable-length parameters in functions can be identified with the vararg
keyword:
fun vars(vararg v: Int) {
for (vt in v) {
print(vt)
}
}
// Test
fun main(args: Array<String>) {
vars(1, 2, 3, 4, 5) // Outputs 12345
}
Lambda (Anonymous Function)
Example of using a lambda expression:
// Test
fun main(args: Array<String>) {
val sumLambda: (Int, Int) -> Int = {x, y -> x + y}
println(sumLambda(1, 2)) // Outputs 3
}
Defining Constants and Variables
Mutable variable definition: var
keyword
var <identifier> : <type> = <initialization value>
Immutable variable definition: val
keyword, a variable that can only be assigned once (similar to variables final in Java)
val <identifier> : <type> = <initialization value>
Both constants and variables can be uninitialized, but they must be initialized before they are referenced.
The compiler supports automatic type inference, meaning the type can be omitted during declaration, and the compiler will determine it.
val a: Int = 1
val b = 1 // The system automatically infers the variable type as Int
val c: Int // If not initialized at the time of declaration, the variable type must be provided
c = 1 // Explicit assignment
var x = 5 // The system automatically infers the variable type as Int
x += 1 // Variable is modifiable
Comments
Kotlin supports single-line and multi-line comments, as shown below:
// This is a single-line comment
/* This is a multi-line
block comment. */
Unlike Java, block comments in Kotlin allow nesting.
String Templates
The $
symbol represents a variable name or value.
$varName
represents the value of a variable.
${varName.fun()}
represents the return value of a variable's method:
var a = 1
// Simple name in template:
val s1 = "a is $a"
a = 2
// Any expression in template:
val s2 = "${s1.replace("is", "was")}, but now is $a"
NULL Checking Mechanism
Kotlin's null safety design requires null checks for declared nullable parameters. There are two ways to handle this: adding !!
after the field to throw a null exception like in Java, or adding ?
after the field to return a value of null or to use with ?:
for null checks.
```kotlin // A question mark after the type