KOTLIN DOCS
KOTLIN DOCS
Output:
Hello, Geeks! This is Kotlin tutorial.
Kotlin
fun main(args
: Array<String>)
println("GeeksforGeeks")
print("GeeksforGeeks - ")
Output:
GeeksforGeeks
A Computer Science portal for Geeks
GeeksforGeeks - A Computer Science portal for
Geeks
Print literals and Variables –
Kotlin
return a + b
var a = 10
var b = 20
var c = 30L
println("$marks")
Output:
Sum of {10} and {20} is : 30
Long value is: 30
marks
40.4
Kotlin Expression –
XYZ {….})
Note: In Kotlin every function returns a value
atleast Unit, so every function is an expression.
return a+b
val a = 10
val b = 5
var mul = a * b
println(sum)
println(mul)
Output:
15
50
Kotlin else if
Use else if to specify a new condition if the first
condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is
true
} else if (condition2) {
// block of code to be executed if the condition1 is
false and condition2 is true
} else {
// block of code to be executed if the condition1 is
false and condition2 is false
}
Example
val time = 22
if (time < 10) {
println("Good morning.")
} else if (time < 20) {
println("Good day.")
} else {
println("Good evening.")
}
// Outputs "Good evening."
Kotlin If..Else Expressions
In Kotlin, you can also use if..else statements as
expressions (assign a value to a variable and return
it):
Example
val time = 20
val greeting = if (time < 18) {
"Good day."
} else {
"Good evening."
}
println(greeting)
Kotlin when
Instead of writing many if..else expressions, you
can use the when expression, which is much easier
to read.
It is used to select one of many code blocks to be
executed:
Example
Use the weekday number to calculate the weekday
name:
val day = 4
Kotlin Break
The break statement is used to jump out of a loop.
This example jumps out of the loop when i is equal
to 4:
Example
var i = 0
while (i < 10) {
println(i)
i++
if (i == 4) {
break
}
}
Try it Yourself »
Kotlin Continue
The continue statement breaks one iteration (in the
loop), if a specified condition occurs, and
continues with the next iteration in the loop.
This example skips the value of 4:
Example
var i = 0
while (i < 10) {
if (i == 4) {
i++
continue
}
println(i)
i++
}
Kotlin For Loop
Kotlin Functions
Parameters in Function
b of Integer type
Body of Function
Here in the body we perform the operations to be
performed in the function like in the above
Example:
val c = a + b
Return Value
Return value is the value which is returned after
the operation is performed in the function. In
above example c is the value which is returned.
Types of Functions in Kotlin
In Kotlin, there are two types of functions:
User-defined function
function.
Kotlin function mul() to Multiply two Numbers
having same type of Parameters: