In the past month I did some work on Kotlin and some article you can see on this trending topic. So today I am here with the list of daily used Kotlin code snippet which every developer need to know.
It is a collection of random and frequently used idioms in Kotlin. If you have a favorite idiom, contribute it by sending a comment below.
List of Daily used Kotlin Code Snippet:
1. Creating DTOs (POJOs/POCOs)data class Customer(val name: String, val email: String)
This provides a Customer
class with the following functionality: getters (and setters in case of var{: .keyword }s).
equals()
hashCode()
toString()
copy()
component1()
component2()
For all properties (see Data classes).
Do you know: What is Kotlin Native?
2. Default values for function parametersfun foo(a: Int = 0, b: String = "") { ... }
3. Filtering a listval positives = list.filter { x -> x > 0 }
Or alternatively, even shorter:
val positives = list.filter { it > 0 }
Do you use this: Koin – Kotlin Dependency Injection
4. String Interpolationprintln("Name $name")
5. Instance Checkswhen (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
6. Traversing a map/list of pairsfor ((k, v) in map) {
println("$k -> $v")
}
(k, v)
can be called anything.
for (i in 1..100) { ... } // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
Recommended article: Top 30 Android Tools Every Developer should Know
8. Read-only listval list = listOf("a", "b", "c")
9. Read-only mapval map = mapOf("a" to 1, "b" to 2, "c" to 3)
10. Accessing a mapprintln(map["key"])
map["key"] = value
11. Lazy propertyval p: String by lazy {
// compute the string
}
Did you know: Disadvantage of Kotlin – You must know before use
12. Extension Functionsfun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
13. Creating a singletonobject Resource {
val name = "Name"
}
14. If not null shorthandval files = File("Test").listFiles()
println(files?.size)
15. If not null and else shorthandval files = File("Test").listFiles()
println(files?.size ?: "empty")
Read this too: 5 cool things you probably don’t know about Kotlin
16. Executing a statement if nullval data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
17. Execute if not nullval data = ...
data?.let {
... // execute this block if not null
}
18. Map nullable value if not nullval data = ...
val mapped = data?.let { transformData(it) } ?: defaultValueIfDataIsNull
19. Return on when statementfun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
20. ‘try/catch’ expressionfun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// Working with result
}
21. ‘if’ expressionfun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
22. Builder-style usage of methods that return Unitfun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
23. Single-expression functionsfun theAnswer() = 42
This is equivalent to:
fun theAnswer(): Int {
return 42
}
This can be effectively combined with other Kotlin code snippet, leading to shorter code. E.g. with the when{: .keyword } expression:
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
Scratch tutorial: Create Reddit like Android Kotlin app Step by Step
24. Calling multiple methods on an object instance (‘with’)class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle()
with(myTurtle) { //draw a 100 pix square
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
25. Java 7’s try with resourcesval stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
26. Convenient form for a generic function that requires the generic type information/ public final class Gson {
// ...
// public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {g
// ...
inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)
27. Consuming a nullable Booleanval b: Boolean? = ...
if (b == true) {
...
} else {
// `b` is false or null
}
I hope you like this article and found it helpful.
Comments
Please log in or sign up to comment.