Skip to content

Instantly share code, notes, and snippets.

@mnn
Created November 8, 2016 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mnn/3ef2e1bb67a93733a7d293c0fe7e10c2 to your computer and use it in GitHub Desktop.
Save mnn/3ef2e1bb67a93733a7d293c0fe7e10c2 to your computer and use it in GitHub Desktop.
Custom conditional operator in Scala with widening support
import util.Random
import scalaz._
import Scalaz._
import CustomCondOp._
trait Card {
println(s"Constructing ${getClass.getSimpleName}")
}
class BigCard extends Card
class SmallCard extends Card
object Main extends App {
def printCard(card: Card) {println(card.getClass.getSimpleName)}
// Code bellow works fine, but I would prefer less verbose conditional operator (like ?: from JavaScript).
(if (Random.nextBoolean) new BigCard else new SmallCard) |> printCard
// I thought ScalaZ's ?| was meant to be an alternative to if. But following statement fails to compile.
//(Random.nextBoolean ? new BigCard | new SmallCard) |> printCard
// Here is a custom replacement ?|| with automatic widening. Can widen too much though.
(Random.nextBoolean ?| new BigCard | new SmallCard) |> printCard
}
// based on answer from Alexey Romanov on SO
object CustomCondOp {
class Cond[A](x: Boolean, value: => A) {
def |[B >: A](other: => B) = if (x) value else other
}
implicit class CondOp(x: Boolean) {
def ?|[A](y: => A) = new Cond(x, y)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment