Skip to content

Instantly share code, notes, and snippets.

View edreyer's full-sized avatar

Erik Dreyer edreyer

View GitHub Profile
@edreyer
edreyer / Nullable.kt
Last active April 16, 2024 13:24
null handling in both Java and Kotlin
// our data model
data class Person(val name: String, val age: Int, val email: String)
// vanilla Kotlin
fun createPerson(name: String?, age: Int?, email: String?): Person? =
name?.let { n ->
age?.let { a ->
email?.let{ e ->
Person(n, a, e);
}
import kotlinx.coroutines.launch
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.runBlocking
// inspired by: https://dzone.com/articles/print-even-and-odd-numbers-using-two-threads-compl
// You can run this in a Kotlin REPL
fun main() = runBlocking {
(1..100).forEach {
@edreyer
edreyer / workflow.kt
Last active August 26, 2021 03:37
Kotlin UseCase impl
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.reactor.awaitSingle
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
typealias Workflow<R> = suspend () -> Result<R>
typealias MonoWorkflow<R> = suspend () -> Mono<R>
@edreyer
edreyer / AsyncExample.java
Last active July 15, 2020 15:10
Spring Boot @async and Exceptions
import io.vavr.control.Try;
import java.util.concurrent.Future;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
class Foo {}
interface FooService {
/** Returns Future<Try<T>> for better exception handling */
@Async
@edreyer
edreyer / quantity.sc
Created May 14, 2020 14:31
ADT basics
sealed trait Quantity
object Quantity {
final case class UnitQuantity private (units: Int) extends Quantity
final case class WeightQuantity private (kgs: Double) extends Quantity
// factory with validation
object UnitQuantity {
def create(units: Int): Either<ValidationError, UnitQuantity> =
if (units <= 0) Either.left(ValidationError("units must be positive"))
@edreyer
edreyer / Option.java
Created October 15, 2019 01:07
Adds some useful operations to Java 8's Optional
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
/**
@edreyer
edreyer / ImperativeToFunctionalState.java
Created October 10, 2019 04:37
State Monad: Imperative to Functional
package techtalk;
import com.jnape.palatable.lambda.adt.hlist.Tuple2;
import com.jnape.palatable.lambda.functions.Fn1;
import com.jnape.palatable.lambda.functions.Fn2;
import io.vavr.collection.HashMap;
import io.vavr.collection.Map;
import static com.jnape.palatable.lambda.adt.hlist.HList.tuple;
import static com.jnape.palatable.lambda.functor.builtin.State.state;