Skip to content

Instantly share code, notes, and snippets.

@jacobmoncur
jacobmoncur / Room.kt
Last active July 19, 2017 17:07
Sample of Room using Kotlin.
class App: Application() {
companion object {
lateinit var database: MyDatabase
}
override fun onCreate() {
super.onCreate()
App.database = Room.databaseBuilder(this, MyDatabase::class.java, "my-database").build()
}
}
@jacobmoncur
jacobmoncur / KotlinBrownBag.kt
Created February 22, 2016 22:10
Kotlin Brown Bag
Kotlin! (kotlinlang.org)
// Kotlin is...
// A Statically typed programming language
// for the JVM,
// Android
// and the browser
class Cacheable<T>(val key: String, val default: T, val valueSet: (value: T) -> Unit = {}) {
val type: Type = object : TypeToken<T>(){}.type
var value: T by Delegates.observable(default) { prop, old, new ->
new?.let { valueSet(it) }
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
if(value == null) { value = Cacher.getFromCache(key, default, type) }
return value ?: default

Variables

val firstName: String = "Luke"

val lastName = "Skywalker" // `String` type is inferred


val immutableInt = 20 // `val` is immutable

Nullable

// Optional listener
listenerInterface?.notifyOfSomething()


// `elvis operator` ?: allows for default value
val likeCount = comment?.likes ?: 0

Delegated Properties

class Example {
    var p: String by Delegate()
}


class Delegate {
    operator fun getValue(refr: Any?, prop: KProperty<*>): String {

When

when(currentButtonState){
    ButtonState.GONE -> setupGoneButton(duration)
    ButtonState.BEGIN -> setupStartButton(duration)
    ButtonState.PROGRESS -> setupProgress()
    ButtonState.SUCCESS -> setupSuccessButton()
}

Extension Functions

Animator anim = ObjectAnimator.ofFloat(mainView, "translationY", 500.f);
anim.setInterpolator(new AccelerateDecelerateInterpolator());
anim.setDuration(300);
anim.setStartDelay(100);

Animator anim1 = ObjectAnimator.ofFloat(otherView, "translationY", 200.f);
anim1.setInterpolator(new AccelerateDecelerateInterpolator());
val snapshot = try {
cache[key] ?: return null
} catch (e: IOException) {
// Give up because the cache cannot be read.
return null
}

Lambdas

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        doSomethingAmazing();
    }
});