Instantly share code, notes, and snippets.

View catsSequenceFunctions.scala
import cats.implicits._
val f = (x: Int) => x+1
val g = (x: Int) => x+2
val h = (x: Int) => x+3
// Cats has an Applicative instance for Function1 so you can traverse/sequence it
val l = List(f, g, h).sequence //l : Function1[Int, List[Int]]
l(1) //List(2, 3, 4)
View kafkaClient.scala
import java.util.Properties
import akka.Done
import akka.actor.ActorSystem
import akka.kafka.scaladsl.Producer
import akka.kafka.{ProducerMessage, ProducerSettings}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import cats.effect.IO
import com.sksamuel.avro4s.{FromRecord, RecordFormat, ToRecord}
import org.apache.avro.generic.GenericRecord
View pipe.scala
implicit class AnyEx[T](val v: T) extends AnyVal {
def |>[U](f: T U): U = f(v)
}
//example
def f(l: List[Int]) = l.filter(x => x >1)
def g(l: List[Int]) = l.filter(x => x <3)
List(1,2,3) |> f |> g //List(2)
View TaglessMonadError.scala
import cats._
import cats.implicits._
def loadResult[F[_]](implicit F: MonadError[F, Throwable]): F[String] = {
val resultEitherF: F[Either[Throwable, String]] = ???
val resultF: F[String] = resultEitherF.flatMap(F.fromEither)
resultF.recoverWith{
case error => F.pure(error.getMessage)
}
}
View typeclassExample.scala
//typeclass example
//Note : List already has a sum method working the same way
//List(1,2,3).sum returns 6
//but this example is simpler
// Monoid = summable + neutral element
trait Monoid[T] {
def combine(a: T, b: T): T
def empty: T
View implicitClassExtendingGenericTrait.scala
//example with Generic trait
trait Summable[T] {
def sumWith(other: T): T
}
implicit class StringSummable(s: String) extends Summable[String]{
def sumWith(other: String): String = s + other
}
View structural_typing.ts
interface HasScore {
score: number;
// also works with functions instead of properties
}
let player = { score: 0 };
function addPointsToScore(player: HasScore, points: number): void {
player.score += points;
}
View composeFutureOfNullable.kt
@Test
fun combineNullable() {
fun giveInt(x: Int):Int? = x+1
fun giveInt2(x: Int):Int? = x+2
fun combine(x: Int): Int? = giveInt(x)?.let { giveInt2(it) }
assertEquals(combine(1),4)
}
View optionalFlatten.md

How to retrieve List("a", "b") from a list of optional values

A very common use case when dealing with options...

Scala

val values = List(Some("a"), None, Some("b")).flatten

Java

View observe.js
var names = ['joe', 'bob'];
Object.observe(names, function(changes){
changes.forEach(function(change) {
console.log(change.type, change.name)
});
console.log("names",names);
});