Skip to content

Instantly share code, notes, and snippets.

View orangy's full-sized avatar

Ilya Ryzhenkov orangy

  • JetBrains
  • Tbilisi
View GitHub Profile
@orangy
orangy / using.kt
Created May 2, 2014 12:56
DSL for C#-style using statement
trait Disposable {
fun dispose()
}
fun using(value : Disposable, body : ()->Unit) {
try {
body()
} finally {
value.dispose()
}
@orangy
orangy / event.kt
Last active September 30, 2019 09:45
C#-style events in Kotlin
class Event<T> {
private val handlers = arrayListOf<(Event<T>.(T) -> Unit)>()
fun plusAssign(handler: Event<T>.(T) -> Unit) { handlers.add(handler) }
fun invoke(value: T) { for (handler in handlers) handler(value) }
}
val e = Event<String>() // define event
fun main(args : Array<String>) {
e += { println(it) } // subscribe
data class IBAN(val country: String, val account : String)
// parseIBAN returns nullable IBAN
fun parseIBAN(code : String) : IBAN? {
...
}
val iban = parseIBAN(userInput)
when (iban) {
null -> throw InvalidIBANException()
when(v) {
is Vector -> // here v is of type Vector
is Versor -> // here v is of type Versor
else -> throw UnsupportedTypeException()
}