Search code examples
kotlinkotlin-android-extensions

Throw custom null assertion with !! operator in Kotlin?


I would like to translate the following code from android java to kotlin

 public static void Initialize(Context context) {
        if (mInstance == null) {
            mInstance = new AzureServiceAdapter(context);
        } else {
            throw new IllegalStateException("AzureServiceAdapter is already initialized");
        }
    }

I have read up the difference between ? and !! operators but could not get the expression I wanted. Basically I would like to throw a custom exception when the variable is not null. However, I could not get it to throw a custom exception when using !! as it only throws NPE.

 public fun Initialize(context: Context){
        mInstance!!.AzureServicesAdapter(context) ?: throw IllegalStateException("AzureServiceAdapter is already initialised")
    }

Above is my self converted code to kotlin but I am not sure if this is the right move. Thanks for the help.


Solution

  • You can use the same thing in Kotlin.

     fun Initialize(context: Context) {
            if (mInstance == null) {
                mInstance = AzureServiceAdapter(context)
            } else {
                throw IllegalStateException("AzureServiceAdapter is already initialized")
            }
        }
    

    Keep your code simple and understandable for everyone.