singularity

2.1 Introduction to Kotlin

2.3.1 Variables

2.3.2 Functions

fun methodName(param1: Int, param2: Int): Int {
    return 0
}

import kotlin.math.max

fun largerNumber(num1: Int, num2: Int): Int {
    return max(num1, num2)
}

fun largerNumber(num1: Int, num2: Int): Int = max(num1, num2)


fun largerNumber(num1: Int, num2: Int) = max(num1, num2)

2.4 Flow Control

2.4.1 if Statement

fun largerNumber(num1: Int, num2: Int): Int {
    var value = 0

    if (num1 > num2) {
        value = num1
    } else {
        value = num2
    }
    
    return value
}
    val value = if (num1 > num2) {
        num1
    } else {
        num2
    }
fun largerNumber(num1: Int, num2: Int) = if (num1 > num2) {
        num1
    } else {
        num2
}
fun largerNumber(num1: Int, num2: Int) = if (num1 > num2) num1 else num2

2.4.2 when Statement

fun getScore(name: String) = when (name) {
    "Tom" -> 86
    "Jim" -> 77
    "Jack" -> 95
    "Lily" -> 100
    else -> 0
}
fun checkNumber(num: Number) { 
    when (num) {
        is Int -> println("number is Int")
        is Double -> println("number is Double")
        else -> println("number not support")
    }
}
fun getScore(name: String) = when {
    name.startsWith("Tom") -> 86
    name == "Jim" -> 77
    name == "Jack" -> 95
    name == "Lily" -> 100
    else -> 0
}

2.4.3 Loop Statement

fun main() {
    for (i in 0..10) {
    println(i)
    }
}
fun main() {
    for (i in 0 until 10 step 2) {
        //equivalent to i=i+2 in for-i loop
    println(i)
    }
}
fun main() {
    for (i in 10 downTo 1) {
    println(i)
    }
}

2.5 Object-Oriented Programming

2.5.1 Class and Object

class Person {
    var name = ""
    var age = 0
    fun eat() {
        println("" + age + " years old " + name + " is eating")
    }
}

fun main() {
    val p = Person()
    p.age = 2222
    p.name = "suraj"
    p.eat()
}

2.5.2 Inheritance and Constructor Function

class Student {
    var sno = ""
    var grade = 0
}
open class Person {
    var name = ""
    var age = 0
    fun eat() {
        println("" + age + " years old " + name + " is eating")
    }
}

class Student: Person() {
    var sno = ""
    var grade = 0
}
class Student(val sno: String, val grade: Int) Person() {
}

//then call primary constructor like so:

val student = Student("a123", 5)
class Student(val sno: String, val grade: Int) : Person() {
    init {
        println("sno is " + sno)
        println("grade is " + grade)
    }
}

2.5.3 Interface
2.5.4 Data Class and Singleton
2.6 Lambda Expression 2.6.1 Creation and Iteration of Collection
2.6.2 Functional APIs of Collections
2.6.3 Java Functional API
2.7 Null Safety
2.7.1 Nullable Type
2.7.2 Nullability Check Tools
2.8 Kotlin Tricks
2.8.1 String Interpolation 2.8.2 Function Default Arguments
2.9 Summary