KITRIK
KITRIK

Reputation: 37

What to return if a try catch fails in Kotlin?

I am new to Kotlin and mainly programmed Java before. The Problem is I have this:

private fun createUrl(stringUrl: String): URL? {
    try {
        return URL(stringUrl)
    } catch (e: MalformedURLException) {
        return null
    }
}

That is just the style I was used to in Java. I would just check if the URL is null in the next method, but what is the Kotlin equivalent? What would I return in Kotlin?

Greetings

Upvotes: 0

Views: 1844

Answers (1)

Sam
Sam

Reputation: 5392

You already wrote this in Kotlin, so not entirely sure of your whole question. However, returning URL? is perfect.

Then you can do

mWebURL.set(createUrl(myString))

or

  mWebURL.set(createUrl(myString)?: "alternativeURL")

if you have an observable that is ok accepting null.

Or if you need to take an action on it, you can simply do

createUrl(myString)?.nextAction() //only occurs if not null

or you can use

createURL(myString)?.let{
    //will happen if not null
} 

or

createURL(myString)?.apply{
    //will happen if not null
} 

or of course simple

if(createUrl(myString) == null){
    //will happen if not null
}

Upvotes: 4

Related Questions