Skip to content

Instantly share code, notes, and snippets.

View patrickcousins's full-sized avatar

Patrick Cousins patrickcousins

View GitHub Profile
@patrickcousins
patrickcousins / JobQueueRx.kt
Last active February 20, 2020 23:02
ideas around a fake mini job queue
package com.example.android.lib.rx
import io.reactivex.Observable
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.concurrent.TimeUnit
class JobExample {
val queue = ConcurrentLinkedDeque<Item>()
@patrickcousins
patrickcousins / EnumerateSealed.kt
Last active January 31, 2020 14:43
enumerate the branches of a sealed class up to 2 levels
import kotlin.reflect.KClass
sealed class States {
sealed class StateA : States() {
object One : StateA()
object Two : StateA()
}
sealed class StateB : States() {
object Three : StateB()
fun isRich(person: Person) : Boolean {
causeSideEffect()
readInternalState()
return unexpectedValue
}
fun calculateDiscount(person: Person) : Int {
return when {
over65(person) -> 20
under13(person) -> 10
isRich(person) -> 0
else -> 5
}
}
private fun over65(person: Person) : Boolean {
return person.age > 65
}
private fun under13(person: Person): Boolean {
return person.age < 13
}
private fun isRich(person: Person) : Boolean {
return person.income > 100_000
}
//all the code below is in the file DiscountCalculator.kt
class DiscountCalculator {
//...
}
private fun Person.over65() : Boolean {
return this.age > 65
}
@Test
fun over65() {
val person = Person("test", 70)
assertTrue(person.over65())
}
fun calculateDiscount(person: Person) : Int {
return when {
person.over65() -> 20
person.under13() -> 10
person.isRich() -> 0
else -> 5
}
}
class Person(private val name: String, val age: Int, val income: Int = 0) {
fun over65(): Boolean {
return age > 65
}
fun under13(): Boolean {
return age < 13
}
fun calculateDiscount(person: Person) : Int {
return when {
person.age > 65 -> 20
person.age < 13 -> 10
person.income > 1_000_000 -> 0
else -> 5
}
}