Skip to content

Instantly share code, notes, and snippets.

@ariwaranosai
Created January 13, 2016 11:40
Show Gist options
  • Save ariwaranosai/bc813627de1568eb50c1 to your computer and use it in GitHub Desktop.
Save ariwaranosai/bc813627de1568eb50c1 to your computer and use it in GitHub Desktop.
implicit
trait CanTruthy[A] {
def truthys(a: A): Boolean
}
object CanTruthy {
def apply[A](implicit ev: CanTruthy[A]): CanTruthy[A] = ev
def truthys[A](f: A => Boolean): CanTruthy[A] = new CanTruthy[A] {
def truthys(a: A): Boolean = f(a)
}
}
trait CanTruthyOps[A] {
def self: A
implicit def F: CanTruthy[A]
final def truthy: Boolean = F.truthys(self)
}
object ToCanIsTruthOps {
implicit def toCanIsTruthyOps[A](v: A)(implicit ev: CanTruthy[A]) =
new CanTruthyOps[A] {
def self = v
override implicit def F: CanTruthy[A] = ev
}
}
import ToCanIsTruthOps._
implicit val intCanTruthy: CanTruthy[Int] = CanTruthy.truthys({
case 0 => false
case _ => true
})
def truthyIf[A: CanTruthy, B, C](cond: A)(ifyes: => B)(ifno: => C) =
if (cond.truthy) ifyes
else ifno
println(truthyIf(12){"YES"}{"NO"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment