Kotlin 中的前置条件函数 - 良好实践

Precondition functions in Kotlin - good practices

作为一个 Kotlin 编码新手,我想知道是否有一些好的做法甚至语言结构来声明函数中的前置条件。

在 Java 我一直在使用 Guava 的先决条件检查实用程序:

https://github.com/google/guava/wiki/PreconditionsExplained

经过进一步调查,我发现了 require 函数:

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/require.html

这是通常用于检查函数前提条件的内容吗?

当然可以。您可以在 Preconditions.kt. In addition to the require function, there are requireNotNull, check & checkNotNull 函数中找到所有先决条件。

由于文档在 Kotlin 中对其描述不佳,但您可以进一步查看 jdk 中的 Objects#requireNonNull 文档。

Checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors.

我使用标准库中的 assert()require()

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/assert.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/require.html

实际上,'require' 似乎不会被继承——也就是说,如果子类重写了一个具有 'require' 语句的函数,则不会强制执行父函数中的 'require' .真正的先决条件也适用于重新定义继承函数的情况,因此 (IMO) 'require' 并未真正提供完整的 precondition-checking 功能。

(我说 "appears" 因为,作为 kotlin 的新手,我通过一个使用继承的简单实验了解到了这一点——而且我可能错了——例如,编译器中有一个错误导致不正确行为,或者我在 compiling/setup 中做错了什么。不过,我认为这种可能性不大。)