class Money(val cents: Int, val currency: String) {
init {
require(cents >= 0) { "cents must be non-negative, got $cents" }
require(currency.length == 3) { "currency must be ISO 4217 (got $currency)" }
}
}
class Account {
private var open = true
private var balance = 0
fun deposit(amount: Int) {
check(open) { "cannot deposit on closed account" }
require(amount > 0) { "deposit must be positive" }
balance += amount
}
fun close() { open = false }
}
fun firstChar(s: String?): Char {
val nonNull = requireNotNull(s) { "string must not be null" }
// nonNull is smart-cast to String here
return nonNull[0]
}
fun main() {
try { Money(-5, "USD") } catch (e: Exception) { println(e.message) }
println(firstChar("hello"))
}
Create a free account and build your private vault. Share publicly whenever you want.