Skip to content

Instantly share code, notes, and snippets.

View orangy's full-sized avatar

Ilya Ryzhenkov orangy

  • JetBrains
  • Tbilisi
View GitHub Profile
when(v) {
is Vector -> // here v is of type Vector
is Versor -> // here v is of type Versor
else -> throw UnsupportedTypeException()
}
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()
@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
@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()
}
trait Injected<T> {
fun instance() : T
}
trait Imap {
class object : Injected<Imap> {
override fun instance(): Imap {
return ImapImpl()
}
Instead of init-increment-condition "for" statement, we use for-each style: "for (x in 0..10)", compiler optimises as needed.
Declare immutable value with "val" and mutable variable with "var", either in class, function or top-level.
Missing 'With' from Delphi? :) Standard library has "public inline fun <T, R> with(receiver: T, f: T.() → R): R = receiver.f()"
I can't have no fact for today, because type system forbids me from passing null to not-null parameter.
Last functional argument of a method can be passed outside of parentheses: https://gist.github.com/orangy/11474248 <— "using statement" DSL
class Event<T> {
typealias subscriber = (T)->Void
var subscribers = subscriber[]()
func subscribe(body : subscriber) {
subscribers.append(body)
}
func fire(value : T) {
for s in subscribers {
s(value)
}
@orangy
orangy / JsonPath
Last active August 29, 2015 14:03
class JsonObject {
fun get(name : String) : JsonObject {
}
}
class JsonPathBuilder() {
fun String.div(name : String) : JsonPath {
}
trait SelectResult<T> {
val take: Boolean
val value: T
class object {
fun take<T>(value: T) = object : SelectResult<T> {
override val value: T = value
override val take: Boolean = true
}
fun skip<T>() = object : SelectResult<T> {
package x
fun fn(items: List<String?>) {
items.foreach(filter.notNull) { value ->
println("$value")
}
items.foreach(map.indexed) { (index,value) ->
println("$index $value")
}