Jump to content

Assertions: Difference between revisions

→‎{{header|Kotlin}}: Add nuance between assertion, Errors, and checks.
(add Standard ML)
(→‎{{header|Kotlin}}: Add nuance between assertion, Errors, and checks.)
Line 829:
 
=={{header|Kotlin}}==
AssertionsKotlin supports Jva-style assertions. These need to be enabled using java's -ea option for an <code>AssertionError</code> to be thrown when the condition is false. An assertion should generally never fire, and throws an <code>Error</code>. <code>Error</code>s are seldom used in Kotlin (and much less assertions), as they represent catastrophic issues with the program, such as classes failing to load. These are usually only ever raised by the JVM itself, rather than actual user code.
<lang scala>// version 1.0.6 (assert.kt)
 
<lang kotlin>fun main(args: Array<String>) {
val a = 42
assert(a == 43)
Line 842 ⟶ 841:
at AssertKt.main(assert.kt:5)
</pre>
 
A more Kotlin idiomatic approach to checks are the <code>require</code> (and <code>requireNotNull</code>) to check arguments, and the <code>check</code> (and <code>checkNotNull</code>), and <code>error</code> to check state. The former is mostly meant for checking input, and will throw <code>IllegalArgumentException</code>s, whereas the later is meant for state-checking, and will throw <code>IllegalStateException</code>s
 
<lang kotlin>fun findName(names: Map<String, String>, firstName: String) {
require(names.isNotEmpty()) { "Please pass a non-empty names map" } // IllegalArgumentException
val lastName = requireNotNull(names[name]) { "names is expected to contain name" } // IllegalArgumentException
 
val fullName = "$firstName $lastName"
check(fullName.contains(" ")) { "fullname was expected to have a space...?" } // IllegalStateException
return fullName
}</lang>
 
=={{header|Lasso}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.