如何在 Kotlin 中启用断言?
How to enable assertions in Kotlin?
我创建了示例 class 来测试 Kotlin 中的断言
class Assertion {
fun sum(a: Int, b: Int): Int {
assert(a > 0 && b > 0)
return a + b
}
}
fun main(args: Array<String>) {
Assertion().sum(-1, 2)
}
并且正在使用以下选项,但程序不会抛出断言异常。
-ea:AssertionKt
、-ea:Assertion
和 -ea:...
要在 Kotlin 中启用断言,运行 具有 -ea
选项的 JVM,无需任何其他说明符。
在 Kotlin
中,与 Java
不同,断言只能在顶层 enabled/disabled,即通过为 JVM 指定 -ea
选项。
在幕后,Kotlin 中的 assert()
是一个函数,定义在 AssertionsJVM.kt
文件中。 ENABLED
_Assertions
对象中的变量用于确定是否启用断言。
@PublishedApi
internal object _Assertions {
@JvmField @PublishedApi
internal val ENABLED: Boolean = javaClass.desiredAssertionStatus()
}
如果为 _Assertions
class.
启用断言,ENABLED
变量将分配给 true
因此,要在 Kotlin 中打开断言,必须在 JVM 中为
启用断言
- 所有 classes
-ea
- 或一个特定的 class
-ea:kotlin._Assertions
我创建了示例 class 来测试 Kotlin 中的断言
class Assertion {
fun sum(a: Int, b: Int): Int {
assert(a > 0 && b > 0)
return a + b
}
}
fun main(args: Array<String>) {
Assertion().sum(-1, 2)
}
并且正在使用以下选项,但程序不会抛出断言异常。
-ea:AssertionKt
、-ea:Assertion
和 -ea:...
要在 Kotlin 中启用断言,运行 具有 -ea
选项的 JVM,无需任何其他说明符。
在 Kotlin
中,与 Java
不同,断言只能在顶层 enabled/disabled,即通过为 JVM 指定 -ea
选项。
在幕后,Kotlin 中的 assert()
是一个函数,定义在 AssertionsJVM.kt
文件中。 ENABLED
_Assertions
对象中的变量用于确定是否启用断言。
@PublishedApi
internal object _Assertions {
@JvmField @PublishedApi
internal val ENABLED: Boolean = javaClass.desiredAssertionStatus()
}
如果为 _Assertions
class.
ENABLED
变量将分配给 true
因此,要在 Kotlin 中打开断言,必须在 JVM 中为
启用断言- 所有 classes
-ea
- 或一个特定的 class
-ea:kotlin._Assertions