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.
?in order to explicitly make a variable nullable, likevar videoRecord1: VideoRecord?. Currently, thevideoRecord1cannot benull, which makes the warning correct.