Skip to content

Instantly share code, notes, and snippets.

@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
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) =
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
implicit class Func1Sugar[A,B](f: Function1[A, Option[B]]) {
def apply(a: Option[A]): Option[B] = a.flatMap(f)
}
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)
}
@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 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 / val-vs-lazy-val.scala
Last active November 11, 2022 10:29
val vs. lazy val for implicit class's in Scala
implicit class StringOps(s: String) {
val one = { println("one"); "one" }
val two = { println("two"); "two" }
lazy val three = { println("three"); "value" }
}
scala> "asdf".three
one
@tstone
tstone / fitler-first-vs-distinct-after.scala
Last active August 29, 2015 14:02
A little performance test for two approaches to resolving duplicates between two lists
// -- Measuring ---
def time[A](label: String, count: Int = 100)(block: => A): Long = {
// the first test run on the console is compiling it
block
// Take the average of <count> runs
(1 to count).toSeq.map { i =>
val t0 = System.nanoTime()
block
@tstone
tstone / gist:cb57355fc70cf6661cd9
Last active August 29, 2015 14:00
Twirl conversions
// bool.scala.html
@(param: Boolean)
<h1>Value: @param</h1>
// index.scala.html
@bool(Some(false))
@bool("false")