Skip to content

Instantly share code, notes, and snippets.

@banshee
Created November 9, 2020 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save banshee/43ad1300bd73093127284d9bc26aea40 to your computer and use it in GitHub Desktop.
Save banshee/43ad1300bd73093127284d9bc26aea40 to your computer and use it in GitHub Desktop.
package com.banshee.kotlinsamplecode
class KotlinSample {
data class Holder(val x: Int, val s: String)
companion object {
// one of these for all instances of KotlinSample
}
val x = com.banshee.kotlinsamplecode.KotlinSampleObject.fn("whatever")
fun fn() {
// Destructuring https://kotlinlang.org/docs/reference/multi-declarations.html
val (h1, h2) = Holder(1, "stuff")
// when is better than most languages switch statements,
// but it's not pattern matching like Scala
when {
x == 1 -> "one"
else -> "default"
}
when (x) {
1 -> "one"
else -> "default"
}
// you can introduce a binding in the when argument
val result: Int = when (val t = x) {
1 -> t
else -> t + 1
}
}
}
// object creates a singleton (per classloader though; that's not relevant for Android)
object KotlinSampleObject {
// Type parameters are specified with <T>
fun <T> fn(t: T): Int {
return 3
}
inline fun <reified T> inlineFn(x: T): T {
return x
}
}
object ScopeFunctions {
// https://kotlinlang.org/docs/reference/scope-functions.html
fun samples() {
// let, run, with, apply, and also.
val letResult: Int = "something".let {
// it is "something"
// returns the result of the block
3
}
val runResult: Int = "something".run {
// this is "something"
// returns the result of the block
3
}
val withResult: Int = with("something") {
// this is "something"
// returns the result of the block
length
}
// apply and also are for fluent calls - they return the context object
val applyResult: String = "something".apply {
// this is "something"
// returns "something"
}
val alsoResult: String = "something".also {
// it is "something"
// returns "something"
}
// you can also use run to run a block
val runResultByItself = run {
1
2
3
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment