Kotlin - Essentials

 // Package definition and imports 

package my.demo
import kotlin.text.*


// Program entry point
fun main(){
val a = 2 // immutable
var b = 3 // mutable
println("Hi Kotlin!")
}

// Function
fun sum(a: Int, b: Int): Int {
return a+b
}

// Classes
open class House

class Room(var number: Int, var size: RoomSize){

}

data class RoomSize(
var height : Double,
var weight : Double
)
fun main(){
var str = "Ram is Young"
var str2 = str.replace("is", "was")
println(str)
println(str2)
}

// Conditional Expressions
fun maxOf(a: Int, b: Int): Int =
if (a > b) a else b

// Loop

fun printAllItemsInList(){
val items = listOf<String>("Ronaldo", "Messi", "Rooney", "Gerad")
for ( i in items) println(i)
// forEach is used to iterate with Collections because it returns the object
items.forEach { items -> println(items) }

// while loop
var index = 0
while (index < items.size ) println(items[index])

}

// When Expression
fun describe(obj: Any): String{
return when(obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a String"
else -> "Unknown"
}
}

// Check number is within range
fun checkRange(number: Int): Boolean =
if (number in 1..100) true else false

// COLLECTIONS
fun checkIfCollectionContainsObject(){
val items = setOf("apple", "banana", "mango")
// sample start
when {
"orange" in items -> {
// do something
println("Orange is Orange")
}
"apple" in items -> println("apple is red")
}
// sample end
}

// Lambda expression to map collections
fun filterTheCollections(){
val fruits = listOf("apple", "banana", "mango", "peach")
fruits.filter { it.startsWith("a") }
.sortedBy { it }
.map { it.uppercase() }
.forEach {
print(it)
}
}






Comments

Popular Posts