Some Scala Randomness

I thought it’d be a fun exercise to implement a ?: operator for Scala, like the one Java has:

boolValue ? ifTrue : ifFales

I turned it into a ?! operator, though, because Scala didn’t like me trying to define a method called ‘:’.

implicit class FancyBoolean(val b: Boolean) {

	def ?[T] (ifTrue: => T) = if (b) {
		new TrueBranch[T] {
			override def ![A >: T, F <: A](ifFalse: => F): A = ifTrue
		}
	} else {
		new TrueBranch[T] {
			override def ![A >: T, F <: A](ifFalse: => F): A = ifFalse
		}
	}

	trait TrueBranch[T] {

		def ![A >: T, F <: A] (ifFalse: => F): A
	}
}

Let’s see how this stuff behaves:

scala> true ? 1 ! 2
res2: Int = 1

scala> false ? 1 ! 2
res3: Int = 2

scala> false ? 1 ! "Hi!"
res4: Any = Hi!

scala> true ? println("Evaluated true!") ! println("Evaluated false!")
Evaluated true!

Nice :)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s