[Kotlin] Basic syntax
Kotlin Basic syntax
Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. Kotlin is designed to interoperate fully with Java, and the JVM version of Kotlin’s standard library depends on the Java Class Library, but type inference allows its syntax to be more concise.
Package definition and imports
Package specification should be at the top of the source file.
1 | package my.demo |
It is not required to match directories and packages: source files can be placed arbitrarily in the file system.
See Packages - https://kotlinlang.org/docs/packages.html.
Program entry point
An entry point of a Kotlin application is the main
function.
1 | fun main() { |
Another form of main
accepts a variable number of String
arguments.
1 | fun main(args: Array<String>) { |
Print to the standard output
print
prints its argument to the standard output.
1 | print("Hello ") |
println
prints its arguments and adds a line break, so that the next thing you print appears on the next line.
1 | println("Hello world!") |
Functions
A function with two Int parameters and Int return type.
1 | fun sum(a: Int, b: Int): Int { |
A function body can be an expression. Its return type is inferred.
1 | fun sum(a: Int, b: Int) = a + b |
A function that returns no meaningful value.
1 | fun printSum(a: Int, b: Int): Unit { |
Unit return type can be omitted.
1 | fun printSum(a: Int, b: Int) { |
See Functions - https://kotlinlang.org/docs/functions.html.
Variables
Read-only local variables are defined using the keyword val
. They can be assigned a value only once.
1 | val a: Int = 1 // immediate assignment |
Variables that can be reassigned use the var
keyword.
1 | var x = 5 // `Int` type is inferred |
You can declare variables at the top level.
1 | val PI = 3.14 |
See also Properties - https://kotlinlang.org/docs/properties.html.
Creating classes and instances
To define a class, use the class
keyword.
1 | class Shape |
Properties of a class can be listed in its declaration or body.
1 | class Rectangle(var height: Double, var length: Double) { |
The default constructor with parameters listed in the class declaration is available automatically.
1 | val rectangle = Rectangle(5.0, 2.0) |
Inheritance between classes is declared by a colon (:
). Classes are final
by default; to make a class inheritable, mark it as open
.
1 | open class Shape |
See classes and objects and instances.
Comments
Just like most modern languages, Kotlin supports single-line (or end-of-line) and multi-line (block) comments.
1 | // This is an end-of-line comment |
Block comments in Kotlin can be nested.
1 | /* The comment starts here |
See Documenting Kotlin Code for information on the documentation comment syntax.
String templates
1 | var a = 1 |
See String templates - https://kotlinlang.org/docs/basic-types.html#string-templates for details.
Conditional expressions
1 | fun maxOf(a: Int, b: Int): Int { |
In Kotlin, if
can also be used as an expression.
1 | fun maxOf(a: Int, b: Int) = if (a > b) a else b |
See if -expressions - https://kotlinlang.org/docs/control-flow.html#if-expression.
for loop
1 | val items = listOf("apple", "banana", "kiwifruit") |
or
1 | val items = listOf("apple", "banana", "kiwifruit") |
See for loop - https://kotlinlang.org/docs/control-flow.html#for-loops.
while loop
1 | val items = listOf("apple", "banana", "kiwifruit") |
See while loop - https://kotlinlang.org/docs/control-flow.html#while-loops.
when expression
1 | fun describe(obj: Any): String = |
See when expression - https://kotlinlang.org/docs/control-flow.html#when-expression.
Ranges
Check if a number is within a range using in
operator.
1 | val x = 10 |
Check if a number is out of range using !in
operator.
1 | val list = listOf("a", "b", "c") |
Iterate over a range.
1 | for (x in 1..5) { |
Or over a progression.
1 | for (x in 1..10 step 2) { |
See Ranges and progressions - https://kotlinlang.org/docs/ranges.html.
Collections
Iterate over a collection.
1 | for (item in items) { |
Check if a collection contains an object using in
operator.
1 | when { |
Using lambda expressions to filter
and map
collections:
1 | val fruits = listOf("banana", "avocado", "apple", "kiwifruit") |
See Collections overview - https://kotlinlang.org/docs/collections-overview.html.
Nullable values and null checks
A reference must be explicitly marked as nullable when null
value is possible. Nullable type names have ?
at the end.
Return null
if str does not hold an integer:
1 | fun parseInt(str: String): Int? { |
Use a function returning nullable value:
1 | fun printProduct(arg1: String, arg2: String) { |
or
1 | // ... |
See Null-safety - https://kotlinlang.org/docs/null-safety.html.
Type checks and automatic casts
The is
operator checks if an expression is an instance of a type. If an immutable local variable or property is checked for a specific type, there’s no need to cast it explicitly:
1 | fun getStringLength(obj: Any): Int? { |
or
1 | fun getStringLength(obj: Any): Int? { |
or even
1 | fun getStringLength(obj: Any): Int? { |
See Classes - https://kotlinlang.org/docs/classes.html and Type casts - https://kotlinlang.org/docs/typecasts.html.
References
[1] Get started with Kotlin—Kotlin - https://kotlinlang.org/docs/basic-syntax.html