Kotlin Crash Note

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More β†’

Cheat Sheet

  • Random number from 0 to 200
    ​​​​(0..200).random()
    
  • Random UUID
    ​​​​UUID.randomUUID().toString()
    
  • Hash the content
    ​​​​title.hashCode().toString()
    
  • padLeft
    ​​​​val seconds:String = "9"
    ​​​​print(seconds.padLeft(2,'0')) // 02
    ​​​​print(seconds.padStart(2,'0')) // 20
    

Generic Type

Image Not Showing Possible Reasons
  • The image was uploaded to a note which you don't have access to
  • The note which the image was originally uploaded to has been deleted
Learn More β†’

Like Any in Typescript
accept any type

fun <T> printItem(item: T) {
    println("Item: $item")
}

fun main() {
    printItem("Hello") // Item: Hello
    printItem(42)      // Item: 42
    printItem(true)    // Item: true
}

Scope

Reference article

apply

for simplified the code by avoid writing the object over and over again, apply pass the object it self into the scope

class Person {
    var name: String = "name"
    var age: Int = 16
}

val person = Person()
person.apply {
    name = "elias"
    age = 18
}

let

let pass the object value to the scope and return the value

val name = "elias"
val uppercaseName = name.let {
    it.toUpperCase()
}

run

run is kind of like apply but with return value

// extend `apply` variable person

val welcomeMessage = person.run {
    name = "elias"
    age = 18
    "My name is $name and i'm $age years old"
}

with

With required, a value must be passed, which will be provided to scope within the parentheses, and it will have a return value.

  • syntax example
val numbers = mutableListOf(1, 2, 3)

val sum = with(numbers) {
    add(4)
    add(5)
    sum() // <- return 15
}

println(sum) // <- 15

also

After completing the job, move on to something else

val numbers = mutableListOf("one", "two", "three")
numbers
    .also { println("The list elements before adding new one: $it") }
    .add("four")

takeIf

If the condition returns true, execute the syntax after it

  • EX: if eliaschen is more than 5 characters than go uppercase and print it out
val name = "eliaschen"
name.takeIf({it.length > 5})?.toUpperCase().let(::println)

takeUnless

the opposite of takeIf, it only excute the syntax after it when the condition return fasle