This is something for which to be very careful with the toString() function, because it is very easy to just use that extension function on a nullable object and not realize that you’re not properly handling a null value. That’s why our code compiles and runs.īut it crashes if navIdToURL returns null because we pass in the malformed URL string “null” to navigateToUrl(). What’s happening is toString() is intercepting the nullable object and always returning a non-null object. Instead, we’re using the Kotlin extension function kotlin.toString() which allows for a null receiver. We’re not actually using the toString() member function as overridden by the URL class (not directly, that is). It has to do with the toString() function that we’re using. And yet, we’re passing the value returned from navIdToURL, which allows nulls, right into this non-null parameter. One of the nice things about Kotlin is that it forces you to deal with nullable types when you try to use them in non-nullable places. But we’re totally ignoring the fact that it can return null. This works fine if navIdToURL() returns a non-null value. So we write our code to get the URL and pass it to navigateToUrl(): navigateToUrl(URLResolver().navIdToUrl(navId).toString()) And there’s one more catch: the navIdToURL() function can return null if it can’t find a matching URL for the given navigation ID. We can do that with the venerable toString() function. We then need to pass that URL to a navigation function navigateToUrl(urlString: String), but that navigation function needs a string version of it (odd, yes, but let’s say it’s an API we don’t control ). Let’s imagine we have a function navIdToURL(navId: Int): URL?that takes a “navigation ID” and converts it into a URL. Wanted to share something that has bitten me with Kotlin’s toString(): be careful of using it on nullable types!
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |