This notation has the benefit that | is often used for type unions (in match statements), which is like an OR for types, while & could be used for type intersections, a type AND.
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.
objectMain{defmain(args:Array[String]):Unit={valn=0if(n==0)println(s"$n == 0 is true")elseprintln(s"${3/n}")}}
with this
importImplicits._objectMain{defmain(args:Array[String]):Unit={valn=0((n==0)?true|:n)match{caseLeft(v)=>println(s"$n == 0 is $v")caseRight(v)=>println(s"${3/v}")}}}
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I found the same inconvenience when working with Scala, the ternary operator just does not exist. Thanks for sharing your interesting implementations.
My opinion is, I tend to separate
Either
and ternary operator since it loses the conciseness when used together.My preference:
This is nicer, but it only works if
ifTrue
andifFalse
have the same type. You could do something likeThis notation has the benefit that
|
is often used for type unions (inmatch
statements), which is like an OR for types, while&
could be used for type intersections, a type AND.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
with this
The conciseness is obvious.
Fair enough! So what you're saying is you'd have the
ifTrue
andifFalse
themselves returnEither
s, if necessary, likeIs that right?
I wonder if there's an implicit conversion that would let us do away with the
Left()
andRight()
...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.