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
Foso
08/23/2020, 8:46 AM
What's wrong with returning "Path?" ?
m
Milan Hruban
08/23/2020, 8:55 AM
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
nanodeath
08/23/2020, 3:03 PM
btw you can just say
return parent?.takeIf { Files.exists(it) }
ā 2
f
frank
08/23/2020, 6:28 PM
@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.