You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
funmain(args:Array<String>) {
println("Fresh Minds!")
}
// args can be omittedfunmain() {
println("Fresh Minds!")
}
Declaring a function
funsum(a:Int, b:Int): Int {
return a + b
}
// Single expression functionfunsum(a:Int, b:Int) = a + b
// A function that doesn't return anythingfunprintSum(a:Int, b:Int): Unit {
println("The sum of $a + $b is ${a + b}")
}
// Unit return type can be omittedfunprintSum(a:Int, b:Int) {
println("The sum of $a + $b is ${a + b}")
}
Declaring variables
val firstName:String="Bas"// Read only variablevar age:Int=31// Mutable variableval lastName ="de Groot"// Declaring a variable with type inferenceval weight:Double?=null// Declaring a nullable type
Working with nullable types
val name:String?=null// Prints length or nullprintln(name?.length)
// Prints name.length or default of 5println(name?.length ?:5)
// Prints length or throws a NullPointerExceptionprintln(name!!.length)
Control flow
If expression
if (a > b) {
println("a is greater than b")
} else {
println("b is greater than or equal to a")
}
// If can be used as an expressionval max =if (a > b) {
a
} else {
b
}
When expression
val x:Number=10val message =when (x) {
0->"x is zero"// Equality checkin1..4->"x is between 1 and 4 (inclusive)"// Range check5, 6->"x is five or six"// Multiple valuesisLong->"x is a Long"// Type checkelse->"x is some number"
}
// When expression with predicatesfunpastPresentOrFuture(date:LocalDate, today:LocalDate) =when {
date.isBefore(today) ->"Past"
date.isEqual(today) ->"Present"else->"Future"
}
For loops
for (i in1..100) {
println(i)
}
for (i in100 downTo 0 step 2) {
println(i)
}
// Range combined with forEach
(1..100).forEach { i ->println(i) }
repeat(10) { i ->println(i) }
While loops
// checks the condition and then executes the bodywhile (x >0) {
x--
}
// executes the body and then checks the conditiondo {
val y = fetchData()
} while (y !=null)
Collections
Creating collections
listOf(1, 2, 3)
mutableListOf(1, 2, 3)
setOf(1, 2, 3)
mutableSetOf(1, 2, 3)
arrayOf(1, 2, 3)
mapOf(1 to "one", 2 to "two")
mutableMapOf(1 to "one", 2 to "two")
sequenceOf(1, 2, 3)
Collection processing
listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.filter { it %2==0 } // only even numbers
.map { it *5 } // multiply number by 5
.take(3) // take first 3
.sum() // calculate sum