Skip to content

Instantly share code, notes, and snippets.

View roschlau's full-sized avatar

Robin roschlau

  • Echometer GmbH
  • Ingolstadt, Germany
View GitHub Profile
@roschlau
roschlau / DeferPanicRecover.kt
Last active August 16, 2018 23:34
Implementing the defer, panic and recover functions from golang in Kotlin, because reasons. I have hardly any knowledge of Go, I googled a little bit about how those functions work. The example is copied from https://blog.golang.org/defer-panic-and-recover and results in exactly the same output.
import java.util.Optional
// Actual implementation
fun <T> deferringScope(block: DeferringScope<T>.() -> T): Optional<T> {
val scope = DeferringScope<T>()
try {
scope.result = Optional.of(scope.block())
} catch (e: Throwable) {
scope.error = e.message ?: e.toString()
}
@roschlau
roschlau / GridSpacingDecoration.java
Created September 7, 2016 19:40
An ItemDecoration that assigns even spacing to a grid of items, with the spacing between the items the same size as the outer spacing of the grid.
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class GridSpacingDecoration extends RecyclerView.ItemDecoration {
private int cols;
private int spacing;
public GridSpacingDecoration(int cols, int spacing) {
@roschlau
roschlau / Repeater.kt
Last active March 16, 2017 11:52
A simple repeater that will repeat an action infinitely with a set interval until it is stopped. Uses Coroutines.
class Repeater(val interval: Long,
val context: CoroutineContext = UI,
val block: () -> Unit
) {
private var updatingJob: Job? = null
private val updatingJobLock = Any()
fun start() = synchronized(updatingJobLock) {
if (updatingJob != null && updatingJob!!.isActive) {
return
@roschlau
roschlau / MutableLazy.kt
Last active November 26, 2017 20:50
Lazy Delegate implementation for a mutable, but lazily initialized variable
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Property delegate to allow lazy initialization of a mutable variable.
*/
class MutableLazy<T>(val init: () -> T) : ReadWriteProperty<Any?, T> {
private var value: Optional<T> = Optional.None()
@roschlau
roschlau / event.kt
Last active July 7, 2017 13:32 — forked from orangy/event.kt
C#-style events in Kotlin
class Event<T> {
private val handlers = arrayListOf<(T) -> Unit>()
operator fun plusAssign(handler: (T) -> Unit) { handlers.add(handler) }
operator 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