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?
var videoRecord: VideoRecord? = null
you can initial its variable like this
nullable reference : https://kotlinlang.org/docs/reference/null-safety.html
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:
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()
}
The variable is not final
, so nothing stops you from doing this somewhere in your code:
videoRecord = null
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With