Skip to content

Instantly share code, notes, and snippets.

@BolajiOlajide
Last active July 31, 2024 01:17
Show Gist options
  • Select an option

  • Save BolajiOlajide/8c1a2b20711b358d3465ca5c2539a654 to your computer and use it in GitHub Desktop.

Select an option

Save BolajiOlajide/8c1a2b20711b358d3465ca5c2539a654 to your computer and use it in GitHub Desktop.
learning kotlin synthax
/**
* You can edit, run, and share this code.
* play.kotlinlang.org
*/
fun main() {
val amount = 90
when (amount) {
in 1..10 -> println("in between one and ten")
!in 11..20 -> println("not in between 11 and 20")
125 -> println("is 124")
else -> {
println("default case")
}
}
println(calculateCatAge(1))
println(calCatAgeLamda(1))
showName("Bolaji")
// in kotlin when the last argument in a function is
// another function, it allows you pass the function
// arg as a lambda outside of the argument declaration
// brace
enhancedMessage("Hello Paulo") {
add(12, 12)
}
enhancedMessage("Hello Paulo") { 12 }
// This is an immutable list. `listOf` lists cannot be mutated
val myListOfNames = listOf("James", "Paul", "Rafael", "Gina")
println(myListOfNames)
for (item in myListOfNames) {
println("$item <====")
}
myListOfNames.forEach { it ->
println("$it in for each")
}
val myMutableList = mutableListOf(12, 40, 34)
myMutableList.add(45)
println(myMutableList)
println("Number of elements: ${myMutableList.size}")
println("Second element: ${myMutableList[1]}")
// this is immutable
val mySet = setOf("US", "MZ", "AU")
println(mySet)
val myMutableSet = mutableSetOf(1,3,4,5)
myMutableSet.add(8)
myMutableSet.add(3)
println(myMutableSet)
// Maps
// immutable map
val secretMap = mapOf(
"Up" to 1,
"Down" to 2,
"Left" to 3,
"Right" to 4
)
println(secretMap)
println("all keys: ${secretMap.keys}")
println("all keys: ${secretMap.values}")
if ("Up" in secretMap) println("Up is in!")
val myMutableSecretMap = mutableMapOf(
"One" to 1,
"Two" to 2,
"Three" to 3
)f
myMutableSecretMap.put("Four", 4)
myMutableSecretMap["Five"] = 5
println(myMutableSecretMap)
val myNewList = mutableListOf<String>()
myNewList.add("Soso")
// empty collections
val empty = emptyList<String>()
val emptySet = emptySet<String>()
val emptyMap = emptyMap<String, Boolean>()
}
fun calculateCatAge(age: Int): Int = age * 7
val calCatAgeLamda: (Int) -> Int = { age -> age * 7 }
// unit means void in Kotlin
// in a lambda you don't always need to specify the arg, it's available as `it`
val showName: (String) -> Unit = { println(it)}
val add: (Int, Int) -> Int = { a, b -> a + b }
// trailing lambda
fun enhancedMessage(message: String, funAsParameter: () -> Int) {
println("$message ${funAsParameter()}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment