Skip to content

Instantly share code, notes, and snippets.

@CarrotCodes
Last active July 6, 2016 20:02
Embed
What would you like to do?
Kotlin examples
// Data classes
data class Something(val something: String)
val output = Something("test").toString() // Something(something=test)
val equal = Something("test2") == Something("test2") // true
val notEqual = Something("test3") == Something("test4") // false
// Null safety and null coalescing
class UserInfo {
val id: Int
val name: String?
}
val name = userInfo.name ?: "a default name"
// Type inference, operator overloading, mutability of primitives
val emptyThing = emptySet<String>()
val typeInferredThing = setOf("hello", "world")
val mutableThing = mutableSetOf("hello")
mutableThing += "world"
// Expressions
val failableInt: Int? = try {
Integer.parseInt(5)
} catch (e: NumberFormatException) {
null
}
// Functional
val evens = listOf(1, 2, 3, 4, 5).filter { it % 2 == 0 }
// Parameter defaults, named parameters
data class Pizza(val toppings: Set<String> = setOf("cheese", "tomato"))
val defaultPizza = Pizza()
val withOnion = Pizza(toppings = setOf("cheese", "tomato", "onion"))
// Enums, when expressions
enum class ContrivedExample {
FIRST,
SECOND,
THIRD
}
fun convertEnumToString(thing: ContrivedExample): String {
return when (thing) {
ContrivedExample.FIRST -> "first"
ContrivedExample.SECOND -> "second"
else -> "unknown"
}
}
// Smart casting, string interpolation
val thing = "Test"
if (thing is String) {
println("thing is a String with length ${thing.length}")
} else {
println("thing isn't a String")
}
// Ranges
for (i in 0..10) { } // 0 1 ... 10
for (i in 0 until 10) { } // 0 1 ... 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment