Custom getter without return on all paths compiles

2019-05-11 23:53发布

问题:

I wrote this code:

var test: String? = null
    get() {
        field?.also {
            return "has value"
        }
    }

It reaches return only when the field is non-null. Otherwise the body just completes. Nevertheless, this compiles fine and returns null if field is null.

If I change to this:

var test: String? = null
    get() {
        if (field != null)
            return "has value"
    }

now the compiler complains that the block body needs a return statement.

Is this some undocumented feature or a bug?

回答1:

This is indeed a bug, planned to be fixed in 1.3.20.



标签: kotlin