Skip to content

Instantly share code, notes, and snippets.

@lukestewart13
lukestewart13 / ValidationTools.scala
Last active September 4, 2018 22:49
Implicit class helper implementation for String, etc., validations (e.g. for validating dirty JSON)
import cats.instances.option._
import cats.{Id, Monad}
import scala.language.higherKinds
/**
* This class solves the problem where you need to perform essentially the same operation, via implicit classes, upon both raw values (Int, String, etc.) and
* also upon their optional equivalents (Option[Int], Option[String], etc.). Normally, for each operation, you would need to write two implicit classes:
* {{{
* implicit class StringImplicits(s: String) {
@lukestewart13
lukestewart13 / JsonConversion.scala
Last active May 11, 2017 20:29
Macro annotation to generate Play default JSON reads/writes in a case class companion object
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.whitebox
class JsonReads extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro JsonConversion.readsImpl
}
class JsonWrites extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro JsonConversion.writesImpl
@lukestewart13
lukestewart13 / GeneratePartialModel.scala
Last active July 6, 2023 12:18
Macro annotation to generate new partial model inside companion object with optional parameters of annotated model. Also generates a default Play JSON deserializer.
import scala.annotation.StaticAnnotation
import scala.language.experimental.macros
import scala.reflect.macros.whitebox
/**
* Example:
* {{{
* @GeneratePartialModel(fieldsToRestrict = "id")
* case class User(id: Int, name: String, email: Option[String])
*
import java.time.{Clock, Instant, ZoneId}
class NanoClock(private val clock: Clock) extends Clock {
def this() { this(Clock.systemUTC) }
private val initialInstant = clock.instant
private val initialNanos = System.nanoTime
override def getZone: ZoneId = clock.getZone
@lukestewart13
lukestewart13 / Partition.scala
Last active May 28, 2018 14:45
Either partition
@tailrec def partition[A, B](in: List[Either[A, B]], out: (List[A], List[B]) = (Nil, Nil)): (List[A], List[B]) = in match {
case Nil => out
case Left(a) :: tail => partition(tail, (a :: out._1, out._2))
case Right(b) :: tail => partition(tail, (out._1, b :: out._2))
}
package test
import scala.reflect.runtime.universe._
object ReflectionHelpers extends ReflectionHelpers
trait ReflectionHelpers {
protected val classLoaderMirror = runtimeMirror(getClass.getClassLoader)