Some Kotlin Problem with solutions Every developer need to know

Kotlin is all the rage lately. And while I do agree that the language is well thought out, it does have — as with everything else — its flaws.

As we already discuss about disadvantage of Kotlin but today in this article I’ll explain some of the Kotlin problems I encountered and try to help you avoid them.
You have to see : Advantage and why you should switch to Kotlin

Top 9 Kotlin problems with their solution:

The mystery null

Image result for null

In Kotlin you can write your code as if null never existed and this can make you forget that null is omnipresent but it hides. Let’s look at this simple and seemingly innocent class:
  1. class Foo {
  2. private val c: String
  3. init {
  4. bar()
  5. c = ""
  6. }
  7. private fun bar() {
  8. println(c.length)
  9. }
  10. }
If you try to instantiate this, you’ll get a NullPointerException because bartried to access the length of c before it was initialized.
Of course the application logic was flawed here, but you still got an Exception. The worst part of this is that your IDE won’t complain about this.
The takeaway here is that Kotlin will help you in a lot of cases (nearly all) to avoid null, but you can’t forget about it and from time to time you’ll encounter things like this.
For every Kotlin developer : Top 20 Daily used Kotlin Code Snippet

Handling nulls from the JDK

Image result for Handling nulls

Kotlin’s standard library handles nulls fine. But if you use classes from the JDK, you will have to handle possible null pointers from library functions by hand.
Most of the time the Kotlin classes are enough, but sometimes you have to use something like the ConcurrentHashMap:
  1. val map = ConcurrentHashMap<String, String>()
  2. map["foo"] = "bar"
  3. val bar: String = map["foo"]!!
In this case, you have to use the !! operator. But in other cases the nullsafety operator (?) can also work. Nevertheless, if you use Java libraries extensively you’ll have to litter your code with !!s and ?s or write adapters for Java classes. This is something you can’t really avoid.
There’s another more hideous problem you might bump into. When using methods on JDK classes, they can return null and don’t have syntactic sugar like the Map access above.
Source: Kotlin Problems and How to avoid them? 

No comments:

Post a Comment