Skip to content

Instantly share code, notes, and snippets.

View s1monw1's full-sized avatar
☁️
Hello, cloud.

Simon Wirtz s1monw1

☁️
Hello, cloud.
View GitHub Profile
sealed interface Error // implementations in same package and module only
sealed class Mammal(val name: String)
class Cat(val catName: String) : Mammal(catName)
class Human(val humanName: String, val job: String) : Mammal(humanName)
fun greetMammal(mammal: Mammal): String {
return when (mammal) {
is Human -> "Hello ${mammal.name}; You're working as a ${mammal.job}"
is Cat -> "Hello ${mammal.name}"
}
}
fun greetMammal(mammal: Mammal): String {
return when (mammal) {
is Human -> "Hello ${mammal.name}; You're working as a ${mammal.job}"
is Cat -> "Hello ${mammal.name}"
else -> "Hello unknown creature"
}
}
// This does not compile because the `when` is not exhaustive
fun greetMammal(mammal: Mammal): String {
return when (mammal) {
is Human -> "Hello ${mammal.name}; You're working as a ${mammal.job}"
is Cat -> "Hello ${mammal.name}"
}
}
open class Mammal(val name: String)
class Cat(val catName: String) : Mammal(catName)
class Human(val humanName: String, val job: String) : Mammal(humanName)
context(PrintingScope, TimeScope)
fun <K, V> Map<K, V>.customPrint() {
// ...
}
// get type in two different ways
val funType1: KFunction3<PrintingScope, TimeScope, Map<String, String>, Unit> =
Map<String, String>::customPrint
val mapping = mapOf("a" to 1, "b" to 2, "c" to 3)
with(PrintingScope()) {
with(TimeScope()) {
mapping.customPrint()
}
}
class PrintingScope(
val separator: String = "________________"
)
class TimeScope {
fun getCurrentTime(): LocalTime =
LocalDateTime.now().toLocalTime().truncatedTo(ChronoUnit.SECONDS)
}
context(PrintingScope, TimeScope)
class PrintingScope(
val separator: String = "________________"
)
context(PrintingScope)
fun <K, V> Map<K, V>.customPrint() {
forEach { (k, v) ->
println("K: $k")
println("V: $v")
println(separator)
val mapping = mapOf("a" to 1, "b" to 2, "c" to 3)
val customizer = PrintingCustomizer()
// usage
with(customizer){
mapping.customPrint()
}