Skip to content

Instantly share code, notes, and snippets.

⚡️
Tinkering

A Deeper Understanding deeperunderstanding

⚡️
Tinkering
Block or report user

Report or block deeperunderstanding

Hide content and notifications from this user.

Learn more about blocking users

Contact Support about this user’s behavior.

Learn more about reporting abuse

Report abuse
View GitHub Profile
View FinalTry.kt
sealed class Try<T> {
companion object {
operator fun <T> invoke(func: () -> T): Try<T> =
try {
Success(func())
} catch (error: Exception) {
Failure(error)
}
View ExampleWithRecover.kt
fun toPet(values: List<String>): Try<Pet> {
val name = values[0]
val ageTry = Try { values[1].toInt() }.recoverWith { Failure<Int>(Exception("Cannot extract age!")) }
val typeTry = PetType.lookup(values[2]).recover { PetType.Invalid }
return ageTry.flatMap { age -> typeTry.map { type -> Pet(name, age, type) } }
}
enum class PetType(val type: String) {
View TrySequenceExtension.kt
object TrySequence {
operator fun <T> Try<T>.component1(): T = when (this) {
is Success -> this.value
is Failure -> throw this.error
}
}
fun <T> Try.Companion.sequential(func: TrySequence.() -> T): Try<T> {
return Try { func(TrySequence) }
}
View ExamplePartition.kt
fun main() {
val lines = Try {
File("./my-pets.csv").readLines().map { it.split(',') }
}
val pets : Try<TryPartition<Pet>> = lines.map { it.map(::toPet).partitionTry() }
when (pets) {
is Success -> println(pets.value)
View SequentialToPet.kt
fun toPet(values: List<String>) = Try.sequential {
val name = values[0]
val (age) = Try { values[1].trim().toInt() }
val (type) = PetType.lookup(values[2].trim())
Pet(name, age, type)
}
View TryPartition.kt
typealias TryPartition<T> = Pair<List<Success<T>>, List<Failure<T>>>
fun <T> List<Try<T>>.partitionTry() : TryPartition<T> {
return this.partition { it is Success } as TryPartition<T>
}
View BasicExample.kt
fun main() {
val resultA = Try { "Hello, World" }
val resultB = Try { throw Exception("Not Today!") }
println(resultA)
println(resultB)
}
View ExampleWithTraverse.kt
fun main() {
val lines = Try {
File("./my-pets.csv").readLines().map { it.split(',') }
}
val pets : Try<List<Pet>> = lines.flatMap { Try.traverse(it, ::toPet) }
when (pets) {
is Success -> println(pets.value)
View TryTraverse.kt
fun <T, R> Try.Companion.traverse(list: List<T>, transform: (T) -> Try<R>): Try<List<R>> = Try {
val newList = mutableListOf<R>()
for (value in list) {
when(val result = transform(value)) {
is Success -> newList.add(result.value)
is Failure -> throw result.error
}
}
newList
}
View NotSoSimple.kt
fun toPet(values: List<String>): Try<Pet> {
val name = values[0]
val ageTry = Try { values[1].toInt() }
val typeTry = PetType.lookup(values[2])
return ageTry.flatMap { age -> typeTry.map { type -> Pet(name, age, type) } }
}
enum class PetType(val type: String) {
You can’t perform that action at this time.