java - 如果 Kotlin 中的 try catch 失败返回什么?
问题描述
我是 Kotlin 的新手,之前主要编写 Java。问题是我有这个:
private fun createUrl(stringUrl: String): URL? {
try {
return URL(stringUrl)
} catch (e: MalformedURLException) {
return null
}
}
这正是我在 Java 中习惯的风格。我会在下一个方法中检查 URL 是否为空,但 Kotlin 等价物是什么?我会在 Kotlin 中返回什么?
问候
解决方案
你已经在 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
}
推荐阅读
- python - 为什么 collectstatic 不复制我的所有目录?
- javascript - Firestore - 如何根据特定字段检查文档是否存在
- javascript - 错误:应用程序崩溃,退出代码:1
- java - 获取错误'尝试调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'ON andoid app
- python - 批处理将图像的颜色配置文件转换为 python 所需的任何配置文件
- batch-file - 从存储在变量中的多行输出中获取第 m 行的第 n 列
- escaping - ',(引号逗号)在普通 lisp 中
- spring - 如何使用 STOMP 从 Spring WebSocket 服务器向 WebSocket 客户端发送消息?
- apache-kafka - 无法在 Kafka Stream App 的子拓扑之间共享状态存储中的数据
- c++ - Valgrind:数学函数中的“条件跳转或移动取决于未初始化的值”