Search code examples
kotlinnullable

what is the recommended way for using the Kotlin double-bang for nullable class member


In kotlin if the variable is nullable the kotlin will ask for either using !! or check the null before using it. In the case of having nullable class member, inside the class anywhere refereeing this member kotlin will warn for checking the nullable.

class ClassWithNullableMemebr {
      Var nullableMember: OtherClass? = null;

      constructor (obj: OtherClass) {
          nullableMember = obj
      }
      fun foo() {
          nullableMember!!.doSomething()
      }
      fun getTheOtherClassMember : OtherClass {
          return nullableMember!!
      }
 }

If the nullableMember is guaranteed to initialized in constructor, how to avoid the use of !!.

In Java or other language they could check null once and throw if by design the member should never be null. Then inside the class the member will be just be referenced without worry.

Someone suggested do

if (nullableMember != null) {
    nullableMember!!.doSomething()
}

This will still need the !! even after the check, and it makes the code looks not pretty.

For this case really using ?. is not much different than using !! since the nullableMember is assigned in the constructor, and the function return it can not avoid the !!.

I think if this nullableMember is guaranteed not null after instantiate the class the using !! shouldn't be considered to be bad coding style. And there is no other way to avoid it.

Does anyone have suggestion to avoid the use of '!!' in the case like this?


Solution

  • If you are sure that variable will have not-null value, you should define it as not-nullable.

    After this, there are two ways to avoid compiler warning and in sight variable initialization:

    1. Usage of lateinit modifier

    lateinit var nullableMember: OtherClass

    Please note if you try to access this variable before its initialization, exception will be thrown

    1. Usage of notNull() delegate

    var nullableMember: OtherClass by Delegates.notNull()

    Differences between these two you can find here.

    If there is a need to set the value of this variable to null somewhere in the code, I am afraid that you'll have to use !! because there is no nicer way of doing this.