Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create null class object in Kotlin?

In java, we can declare a null class object like this

VideoRecord videoRecord;

After that, we can check if it is null or not

if (videoRecord == null){
    videoRecord = new VideoRecord();
}

I am new to Kotlin and I would like to do the same thing in Kotlin. I have tried this code below.

lateinit var videoRecord1:VideoRecord

if (videoRecord1 == null){
    videoRecord1 = VideoRecord()
}

But it gives me a warning like the condition videoRecord1 == null is always false. How can I make the same thing in Kotlin?

like image 315
salih suat kükrer Avatar asked Mar 01 '23 23:03

salih suat kükrer


2 Answers

var videoRecord: VideoRecord? = null

you can initial its variable like this

nullable reference : https://kotlinlang.org/docs/reference/null-safety.html

like image 80
andika_kurniawan Avatar answered Mar 04 '23 13:03

andika_kurniawan


Depending on what you're trying to achieve, e.g. lazy initialization then this may be more suitable for you than the answer given by andika_kurniawan:

val videoRecord: VideoRecord by lazy { VideoRecord() } 

This will lazily initialize videoRecord the first time it is accessed.

The advantage of this way is that you don't have to check for null when accessing videoRecord, because it cannot be null. This simplifies the usage of that variable significantly. Additionally you can mark videoRecord as val, meaning it is final, so it cannot be overwritten.

The example shown by @andika_kurniawan:

var videoRecord: VideoRecord? = null

Has some caveats and disadvantages:

  1. You always have to check that videoRecord is not null (and it gets tedious), see this example:

    if (videoRecord != null) {
        videoRecord.callAMethod()
    }
    

    The above will not work, because videoRecord defined as nullable, so you need to use the !! operator to tell kotlin that you're sure that the variable is not null:

    if (videoRecord != null) {
        videoRecord!!.callAMethod()
    }
    

    You can of course use other idioms, like the null-safe operator ?.

    videoRecord?.callAMethod()
    

    Or the already mentioned !! operator (which throws an exception when it is null) but this time without a null check:

    videoRecord!!.callAMethod()
    

    You may also use local variables, which simplify the usage (a little bit):

    val videoRecord = videoRecord
    if (videoRecord != null) {
        videoRecord.callAMethod()
    }
    
  2. The variable is not final, so nothing stops you from doing this somewhere in your code:

    videoRecord = null
    
  3. You have to initialize it somewhere, so if you have multiple methods accessing videoRecord you first have to initialize it if it hasn't already been, introducing unnecessary redundancy.

like image 42
Lino Avatar answered Mar 04 '23 12:03

Lino