Package definition and imports
Package specification should be at the top of the source file.
It is not required to match directories and packages: source files can be placed arbitrarily in the file system.
See Packages.
Program entry point
An entry point of a Kotlin application is the main
function.
Another form of main
accepts a variable number of String
arguments.
Print to the standard output
print
prints its argument to the standard output.
println
prints its arguments and adds a line break, so that the next thing you print appears on the next line.
Functions
A function with two Int
parameters and Int
return type.
A function body can be an expression. Its return type is inferred.
A function that returns no meaningful value.
Unit
return type can be omitted.
Variables
Read-only local variables are defined using the keyword val
. They can be assigned a value only once.
Variables that can be reassigned use the var
keyword.
You can declare variables at the top level.
Creating classes and instances
To define a class, use the class
keyword.
Properties of a class can be listed in its declaration or body.
The default constructor with parameters listed in the class declaration is available automatically.
Inheritance between classes is declared by a colon (:
). Classes are final by default; to make a class inheritable, mark it as open
.
open class Shape
class Rectangle(var height: Double, var length: Double): Shape {
var perimeter = (height + length) * 2
}
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.
Block comments in Kotlin can be nested.
See Documenting Kotlin Code for information on the documentation comment syntax.
String templates
See String templates for details.
Conditional expressions
In Kotlin, if
can also be used as an expression.
See if
-expressions.
for loop
or
See for loop.
while loop
See while loop.
when expression
See when expression.
Ranges
Check if a number is within a range using in
operator.
Check if a number is out of range.
Iterate over a range.
Or over a progression.
Collections
Iterate over a collection.
Check if a collection contains an object using in
operator.
Using lambda expressions to filter and map collections:
Nullable values and null checks
null
value is possible. Nullable type names have ?
at the end.or
See Null-safety.
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:
or
or even
0 Comments