Advanced Kotlin Tips on writing good Kotlin code and using what the language has to offer. There are many benefits of using Kotlin; it is concise, safe and most importantly it is 100% interoperable with Java. It also tries to solve some of the limitations of Java.Now is a good time to consider Kotlin for your next big feature or project, because Google finally announced it to be a first-class language for writing Android apps in Google I/O 17.
So here are some advanced Kotlin tips to help you start making use of what the language has to offer and writing good Kotlin code.
1. Singleton
Implementing lazy loaded and thread-safe singletons in Kotlin is really easy, unlike Java where you would have to rely on the complex double-checked locking pattern. And although Java enum singletons are thread-safe, they are not lazy loaded.
You must see this : Kotlin Parcelize – Developer need to know
object Singleton {
var s: String? = null
}
Contrary to a Kotlin class, an object can’t have any constructor, but init blocks can be used if some initialization code is required.
Singleton.s = "test" // class is initialized at this point
The object will be instantiated and its init blocks will be executed lazily upon first access, in a thread-safe way.
2. Utility Functions
Favor Kotlin top-level extension functions over the typical Java utility classes. And for easier consumption within Java code, use @file:JvmName to specify the name of the Java class which would get generated by the Kotlin compiler.
// Use this annotation so you can call it from Java code like StringUtil.
@file:JvmName("StringUtil")
fun String.lengthIsEven(): Boolean = length % 2 == 0
val lengthIsEven = "someString".lengthIsEven()
3. Object Initialization
Use apply to group object initialization statements to allow for cleaner, easier to read code.
// Don't
val textView = TextView(this)
textView.visibility = View.VISIBLE
textView.text = "test"
// Do
val textView = TextView(this).apply {
visibility = View.VISIBLE
text = "test"
}
4. Some more small Kotlin tips just for you!
let()
Using let()
can be a concise alternative for if
. Check out the following code:
val listWithNulls: List<String?> = listOf("A", null)
for (item in listWithNulls) {
if (item != null) {
println(item!!)
}
}
With let()
, there is no need for an if
.
val listWithNulls: List<String?> = listOf("A", null)
for (item in listWithNulls) {
item?.let { println(it) } // prints A and ignores null
}
Hi! I am a robot. I just upvoted you! I found similar content that readers might be interested in:
https://medium.com/default-to-open/kotlin-tips-singleton-utility-functions-group-object-initialization-and-more-27cdd6f63a41
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit