Skip to content

Instantly share code, notes, and snippets.

class BadActor extends Actor {
def recieve = {
case Process(id: Int) => process(id)
}
private def process(id: Int) = {
val result = SomeService.get(id)
result onComplete { value =>
sender ! value
@tstone
tstone / angular-filters.scala
Last active August 29, 2015 14:02
Angular Style Filters in Scala/Twirl
// ---- Presenter Pattern ----
// presenters.scala
object presenters {
implicit class StringPresenter(s: String) {
def reverse = Html(s.reverse)
}
implicit DateTimePresenter(dt: DateTime){
def format(f: String) = DateTimeFormat.forPattern(f).print(dt)
class Foo(x: Int) {
def this(x: String) = this(x.toInt)
}
class Bar(x: Int)
object Bar {
def apply(x: String) = new Bar(x.toInt)
}
implicit class Func1Sugar[A,B](f: Function1[A, Option[B]]) {
def apply(a: Option[A]): Option[B] = a.flatMap(f)
}
trait Example { self =>
def mode(m: String): self.type
}
case class Foo extends Example {
def mode(m: String) = this.copy(mode = m)
}
// abstract type, polymorhpic
class HttpClient {
def GET(url: String)(implicit context: ExecutionContext) = ???
}
class SomeService(http: HttpClient = new HttpClient) {
def getSomething(implicit context: ExecutionContext) = ???
}
class ServiceB {
def foo(arg: String)(implicit context: ExecutionContext) =
@tstone
tstone / either-shortcut.scala
Created July 28, 2014 17:55
A little shortcut around always having to specify Left or Right
implicit def aToEither[A,B](a: A): Either[A, B] = Left(a)
implicit def bToEither[A,B](b: B): Either[A, B] = Right(b)
def f(input: Either[String, Int]) = input match {
case Left(s) => println(s"Hello, $s")
case Right(i) => println(s"You are $i years old")
}
scala> f(10)
You are 10 years old
// long-hand boilerplate:
case class ExampleParams(foo: String, bar: String, baz: String) extends Params {
def withFoo(value: String) = this.copy(foo = value)
def withBar(value: String) = this.copy(bar = value)
def withBaz(value: String) = this.copy(baz = value)
}
trait Person
class Manager extends Person
class Engineer extends Person
val people = Seq(new Engineer, new Manager)
people.map(_.toJson)
// PROBLEM: Implicit lookup is for a Writes[Person], not a Writes[Engineer] and Writes[Manager]
package services.config
import scala.concurrent.Future
import scala.reflect.runtime.universe._
trait ReflectedAttributes {
protected val instanceMirror = runtimeMirror(this.getClass.getClassLoader).reflect(this)
protected val members = instanceMirror.symbol.typeSignature.members