loading...

re: Implementing a Ternary Operator in Scala VIEW POST

TOP OF THREAD FULL DISCUSSION
re: This is nicer, but it only works if ifTrue and ifFalse have the same type. You could do something like object Implicits { implicit class Ternab...
 

I don't oppose the idea of using sum type in ternary operator, you just delegate it to the next procedure to do the pattern matching and there will be no benefit than just using if then else.

Just for comparison, compare this

object Main {
  def main(args: Array[String]): Unit = {

    val n = 0

    if (n == 0) 
      println(s"$n == 0 is true")
    else 
      println(s"${3/n}") 

  }
}

with this

import Implicits._

object Main {
  def main(args: Array[String]): Unit = {

    val n = 0

    ((n == 0) ? true |: n) match {
      case Left(v) => println(s"$n == 0 is $v")
      case Right(v) => println(s"${3/v}") 
    } 

  }
}

The conciseness is obvious.

Fair enough! So what you're saying is you'd have the ifTrue and ifFalse themselves return Eithers, if necessary, like

(3 < 2) ? Left(42) |: Right("forty-two")

Is that right?

I wonder if there's an implicit conversion that would let us do away with the Left() and Right()...

That is a good example to ensure type consistency with minimal effort, you don't need |: and &: at the same time and achieve the same result (Option[Either[T, F]]).

One of my main point here is do not over obsess with data type generalization and construct unnecessary structures.

code of conduct - report abuse