In Java, When I had a function that returned an ob...
# announcements
f
In Java, When I had a function that returned an object and it could not pass the validations inside the function it returned a null value . Then I would checked the method if it returned null for the null-safety What approaches can I use to replace null? • Define Any type in the function and return my object or string etc.. ? • Return empty object ? • Suggestions ... Code for replace null:
Copy code
fun getParentPath(son :String) : Path {
    val parent = Paths.get(son).parent

    return parent?.let {
        if (Files.exists(parent))
            parent
        else null  // need alternative
    } ?: null     //  need alternative
}
👀 1
f
What's wrong with returning "Path?" ?
m
the fact that kotlin distinguishes between nullable and non nullable types doesn't mean you should not use null when appropriate. For your case, I think typical way would be to have
Copy code
fun getParentPathOrNull(son: String): Path?
fun getParentPath(son: String): Path // throws exception when path cannot be determined
3
👍 3
n
btw you can just say
return parent?.takeIf { Files.exists(it) }
2
f
@Milan Hruban Thx, I like it your approach but I'm going to return null in this case, I just realized that the method of API that I'm use it accepts nulls by default.