Shibin Fan
Shibin Fan

Reputation: 9

How to convert this java code with null condition check into Kotlin

Recently I'm trying to convert a Java code snippet into Kotlin. I have a special need in this code to only initialize an object when some condition is met, and I don't what to get the side-effect of this initialization (getting an empty new file) if there is no need to initialize it. However Kotlin doesn't allow for no initialization. Anyone has any idea to solve this? Thanks

Java code

FileOutputStream fos = null;
for (...) {
    if (condition met) {
        if (fos == null) {
            fos = new FileOutputStream(filename);
        }
        fos.write(something);
    }
}

Kotlin code I've tried:

var fos: FileOutputStream?;
for (...) {
    if (condition met) {
        if (fos == null) { // compiler error: not initialized
            fos = FileOutputStream(filename);
        }
    }
    fos.write(something)
}  

Also this

var fosCreated: Boolean = false;
var fos: FileOutputStream?;
for (...) {
    if (condition met) {
        if (!fosCreated) { // compiler error: not initialized
        fos = FileOutputStream(filename);
        fosCreated = true;
    }
    fos.write(something)
}

Upvotes: 0

Views: 208

Answers (1)

Michael Berry
Michael Berry

Reputation: 72294

The problem with:

var fos: FileOutputStream?;

...is that you're not initialising it to anything. (Java would complain about an uninitialised type in the same way.)

You can trivially initialise it to null:

var fos: FileOutputStream? = null

As you discovered in the comment, you'll need to make sure you use fos?.write() rather than fos.write() to satisfy Kotlin's null safety features.

Upvotes: 2

Related Questions