Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何正确地在Kotlin中进行快速故障检测?_Kotlin - Fatal编程技术网

如何正确地在Kotlin中进行快速故障检测?

如何正确地在Kotlin中进行快速故障检测?,kotlin,Kotlin,如果某个特定函数返回null,我希望快速失败。我不认为默认值会使处理变得有意义 以下是代码片段: val entityAttributes = entity.optJSONObject("Attributes") ?: run { LOG.error("Could not find 'Attribute' entry in Entity object") return } 因此,如果entity.optJSONOb

如果某个特定函数返回null,我希望快速失败。我不认为默认值会使处理变得有意义

以下是代码片段:

        val entityAttributes = entity.optJSONObject("Attributes") ?: run {
            LOG.error("Could not find 'Attribute' entry in Entity object")
            return
        }
因此,如果entity.optJSONObjectAttributes返回null,那么它确实会取消opt*,我想从函数范围中转义


我这样做是正确的吗?我是Kotlin的新手,希望尽快习惯做这些事情的正确方法。

您可以像上面那样提前从函数返回。如果您的函数返回的不是Unit,那么您必须返回一些默认值

抛出异常允许您在不返回任何内容的情况下退出函数,但如果您在某个地方没有捕获到异常,则该异常将使程序崩溃。有时,如果错误是不应该发生的,那么这正是您希望发生的,因为这样您将在测试期间捕获它,并能够在发布应用程序之前修复它


使用全局errorcause:Any函数,它将立即抛出IllegalStateException。

如果您没有登录,您可以执行?:return或?:throw IllegalArgumentException。如果您还需要记录日志,另一个选项可能是?:return.allow{log.error…},但这并不是更好的选择,如果您不返回其他值,则需要显式地以单位形式给出返回值。或者,如果entityAttributes==null{…},您也可以使用老式的if-entityAttributes==null{…};在函数的其余部分,编译器将智能地将其强制转换为不可为null。