Skip to content

Instantly share code, notes, and snippets.

import java.math.BigInteger
interface Fibonacci {
fun fib(n: Int): Int
}
object LawfulGood : Fibonacci {
override fun fib(n: Int): Int {
check(n >= 0) { "fib is undefined for negative values: $n" }
return when (n) {
@utkan
utkan / viewModelDelegate.kt
Created May 9, 2019 10:41
viewModelDelegate
inline fun <VM : ViewModel> viewModelFactory(
crossinline f: () -> VM) =
object : ViewModelProvider.Factory {
override fun <T : ViewModel> create(aClass: Class<T>) =
f() as T
}
private val viewModel by lazy {
val factory = viewModelFactory { component.myViewModel() }
ViewModelProviders.of(this, factory)
@utkan
utkan / mapDelegate.kt
Last active April 21, 2019 11:28
Map delegate
class NotificationParams(val map: Map<String, String>) {
val title: String by map
val content: String by map
}
override fun onMessageReceived(message: RemoteMessage?) {
super.onMessageReceived(message)
val data = (message?.data ?: emptyMap()).withDefault { "" }
val params = NotificationParams(data)
@utkan
utkan / OomExceptionHandler.java
Created March 29, 2019 12:30 — forked from pyricau/OomExceptionHandler.java
Dump the heap on OutOfMemoryError crashes in your debug builds.
import android.content.Context;
import android.os.Debug;
import java.io.File;
public class OomExceptionHandler implements Thread.UncaughtExceptionHandler {
private static final String FILENAME = "out-of-memory.hprof";
public static void install(Context context) {
Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
@utkan
utkan / Lol.java
Created March 29, 2019 12:26 — forked from pyricau/Lol.java
import java.util.concurrent.Callable;
public enum Lol implements Callable<CharSequence> {
ಠ_ಠ {
@Override public String call() {
return "Foo";
}
};
sealed class BundleDelegate<T>(protected val key: kotlin.String) : ReadWriteProperty<Bundle, T> {
class Int(key: kotlin.String) : BundleDelegate<kotlin.Int>(key) {
override fun getValue(thisRef: Bundle, property: KProperty<*>) = thisRef.getInt(key)
override fun setValue(thisRef: Bundle, property: KProperty<*>, value: kotlin.Int) {
thisRef.putInt(key, value)
}
}
@utkan
utkan / SimpleDI.kt
Created April 15, 2018 20:21
Another, still undervalued, way to reuse factory methods is by using interface delegation. We could use it in above example this way:
interface Dependency<T> {
var mocked: T?
fun get(): T
fun lazyGet(): Lazy<T> = lazy { get() }
}
class Provider<T>(val init: () -> T) : Dependency<T> {
var original: T? = null
override var mocked: T? = null
override fun get(): T = mocked ?: original ?: init().apply { original = this }
abstract class Provider<T> {
var orginal: T? = null
var mocked: T? = null
abstract fun create(): T
fun get(): T = mocked ?: orginal ?: create().apply {
orginal = this
}
enum class Rank {
TWO, THREE, FOUR, FIVE,
SIX, SEVEN, EIGHT, NINE,
TEN, JACK, QUEEN, KING, ACE;
fun of(suit: Suit) = Card(this, suit)
}
enum class Suit {
HEARTS,