Skip to content

Instantly share code, notes, and snippets.

@geekygecko
Last active May 6, 2023 08:23
Show Gist options
  • Save geekygecko/653c4920d9dc305f8ed433f0942d5d86 to your computer and use it in GitHub Desktop.
Save geekygecko/653c4920d9dc305f8ed433f0942d5d86 to your computer and use it in GitHub Desktop.
Kotlin beginners cheatsheet
fun main(args: Array<String>) {
// when statement
val firstName = "Dan"
val job = when (firstName) {
"Dan", "Jay", "Philip" -> "programmer"
"Jamie" -> "designer"
else -> "boss"
}
println("$firstName is a $job")
// Output: Dan is a programmer
// one line functions
fun fullName(firstName: String, lastName: String) = "$firstName $lastName"
println(fullName("Philip", "Kotlin"))
// Output: Philip Kotlin
// strings
println("what happened".capitalize())
// Output: What happened
println("Kotlin".equals("KOTLIN", ignoreCase = true))
// Output: true
println("Kotlin".contains("LIN", ignoreCase = true))
// Output: true
var name: String? = null;
println(name.equals("Philip", ignoreCase = true))
// Output: false
println(name.isNullOrEmpty())
// Output: true
println(name.isNullOrBlank())
// Output: true
name = " ";
println(name.isNullOrEmpty())
// Output: false
println(name.isNullOrBlank())
// Output: true
var names = "Dan\nJay\nPhilip"
for (name in names.lines()) {
println("> $name")
}
// > Dan
// > Jay
// > Philip
for ((index, name) in names.lines().withIndex()) {
println("${index + 1}. $name")
}
// 1. Dan
// 2. Jay
// 3. Philip
// maps
// readonly map
var legs = mapOf(Pair("dog", 4), Pair("penguin", 2))
println(legs.size)
// Output: 2
println(legs["dog"])
// Output: 4
for ((animal, count) in legs) {
println("$animal = $count")
}
// dog = 4
// penguin = 2
// another way to create the readonly map
legs = mapOf("dog" to 4, "penguin" to 2)
println(legs.size)
// Output: 2
// editable map using a HashMap
legs = hashMapOf("dog" to 4, "penguin" to 2)
println(legs["dog"])
// Output: 4
legs["dog"] = 5
println(legs["dog"])
// Output: 5
// list
// readonly list
listOf(1, 2, 3, 4)
// mutable list
val array = arrayListOf("Hello", "World")
array.add("1")
// set
// readonly set
setOf(1, 2, 3)
// mutable set
hashSetOf(1, 2, 3)
sortedSetOf(1, 2, 3)
// null safety
var message: String? = null
message?.let { println(it) }
// Output nothing
message = "Hello"
message?.let { println(it) }
// Output: Hello
message?.let { name ->
println(name)
}
// Output: Hello
println(null ?: "Default value")
// Output: Default value
println("Hello" ?: "Default value")
// Output: Hello
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment