首页 > 解决方案 > 如果 Kotlin 中的 try catch 失败返回什么?

问题描述

我是 Kotlin 的新手,之前主要编写 Java。问题是我有这个:

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

这正是我在 Java 中习惯的风格。我会在下一个方法中检查 URL 是否为空,但 Kotlin 等价物是什么?我会在 Kotlin 中返回什么?

问候

标签: javaandroidandroid-studiokotlin

解决方案


你已经在 Kotlin 中写过这个,所以不完全确定你的整个问题。但是,返回 URL?是完美的。

然后你可以做

mWebURL.set(createUrl(myString))

或者

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

如果你有一个可以接受 null 的 observable。

或者,如果您需要对其采取行动,您可以简单地执行

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

或者你可以使用

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

或者

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

或者当然很简单

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

推荐阅读