# Kotlin Crash Note

# Cheat Sheet
- Random number from 0 to 200
```kotlin
(0..200).random()
```
- Random UUID
```kotlin
UUID.randomUUID().toString()
```
- Hash the content
```kotlin
title.hashCode().toString()
```
- padLeft
```kotlin
val seconds:String = "9"
print(seconds.padLeft(2,'0')) // 02
print(seconds.padStart(2,'0')) // 20
```
# Generic Type

**Like `Any` in Typescript**
accept any type
```kotlin
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](https://andyludeveloper.medium.com/kotlin%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-7-%E6%A8%99%E6%BA%96%E5%87%BD%E6%95%B8-scope-functions-fd1a1c394a2d)
## `apply`
for simplified the code by avoid writing the object over and over again, `apply` pass the object it self into the scope
```kotlin
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
```kotlin
val name = "elias"
val uppercaseName = name.let {
it.toUpperCase()
}
```
## `run`
`run` is kind of like `apply` but **with return value**
```kotlin
// 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
```kotlin!
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
```kotlin
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
```kotlin
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`