Kotlin is a new programming language that is gaining popularity among developers. While it is still relatively new, Kotlin has already become the preferred language for developing Android applications.
If you’re just getting started with Kotlin, or if you’re looking for code snippets to help speed up your development process, look no further. Code snippets are easy to share with fellow developers, making it easy to collaborate on Kotlin projects. As Kotlin continues to grow in popularity, it is likely that more and more developers will use code snippets to speed up their workflow.
In this blog post, we’ve curated a list of some of our favorite Kotlin code snippets. Whether you’re looking for tips on how to use lambda expressions or how to work with collections, you’ll find everything you need right here.
Array & List
Get the Current Index of for each Loop —
list.forEachIndexed { index, element ->
Log.e("$index", element.toString())
}
Class & Object
Create DTOs —
data class Account(val username: String, val email: String, val password: String, val active: Boolean)
data class Product(
var id: Int,
var description: String,
var price: Long
)
Function
Set Default Values for Function Parameters —
fun myFunction(param1: String, param2: String = "defaultValue") {
// function body goes here
}
fun myFunction(param1: String = "defaultValue1", param2: Boolean = false) {
//do something here
}
Number
Convert Number to String with a Comma for Thousands —
val num = 123456789
val str = String.format("%,d", num) // Result: "123,456,789"
val formattedDouble = String.format("%,.2f", 123456.78d); //"123,456.78"
Add Leading Zeros to a Number —
val num = 123
val formattedNum = String.format("%06d", num)
println(formattedNum) // 000123
val paddedNum = num.toString().padStart(6, "0")
println(paddedNum ) // 000123
val month = "7"..padStart(2, "0")
println(month ) // 07
String
Iterate through a String —
val country = "Sao Tome and Principe";
for (i in 0..country.length-1) {
println(country[i])
}
country.forEach {
println(it)
}
for (i in country.indices) {
println(country[i])
}
val it = country.iterator()
while (it.hasNext()) {
val c = it.next()
println(c)
}
Access Characters of a String —
val str = "Svalbard & Jan Mayen Islands";
println(str[5]) //"a"
println(str[9]) //"&"
for (char in str) {
println(char )
}