To share this page click on the buttons below;
If, then else
It is in C-like style:
if(<condition>) {
}
else if (<condition>) {
}
else if (<condition>) {
}
<...>
else {
}
When
It replaces the switch, case
C statement:
when(<variable>) {
<value1> -> <code1>
<value2> -> <code2>
<value3> -> <code3>
...
<valuen> -> <coden>
else -> <code>
}
when
does not have the falling through mechanism typical of switch,case C statement.
values that are mapped to the same code can be grouped together separated by commas
when(<variable>) {
<value1> -> <code1>
<value2>,<value3>,<value4> -> <code2>
<value5> -> <code3>
...
<valuen>,<valuen+1> -> <coden>
else -> <code>
}
when can be used with ranges (in value1 .. value2
)
when(<variable>) {
in <value1> .. <value2> -> <code1>
in <value3> .. <value4> -> <code2>
<value5> -> <code3>
<...>
<valuen>,<valuen+1> -> <coden>
else -> <code>
}
For
For loop is used to loop over iterable items, like ranges
for(<variable> in <start value> .. <stop value> ){
}
or Arrays
val <array>
for (<value> in <array>){
}
To iterate over an array using array's indexes there are 2 possibilities:
val <array>
for (<index> in <array>.indices){
// here you access the array values with <array>[<index>]
}
or
val <array>
for ( (<index>,<value>) in <array>.withIndex()){
// that make available both index and value
}
While
while (<condition>){
}
Do-While
do {
} while (<condition>)
Continue
With all loops is available continue
(like C ) to skip current iteration and go to the next one.
continue
may be labeled (like a goto
), for example to jump to a next iteration of an outer loop.
<label>@ while (<condition>){
for(<...>) {
continue@<label>
//it jumps to the next while loop
}
}
Break
Also break
(like C) is available to exit loops in advance. Also in the case of break
there is the possibility to have labeled break
.
Functions
fun <function_name>(<argument 1>: <type>, <argument 2>: <type>, ...): <return_type> {
// function body
}
Arguments function can have default arguments in the function declaration. Kotlin supports also name argument so that it is possible to specify in the function call only the name and value of one ore more parameters leaving the other to their default values.
Lambda functions
{ <argument 1>: <type>, <argument 2>: <type>, ... -> <implementation> }
To share this page click on the buttons below;