Created
November 8, 2016 09:36
-
-
Save mnn/3ef2e1bb67a93733a7d293c0fe7e10c2 to your computer and use it in GitHub Desktop.
Custom conditional operator in Scala with widening support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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