Skip to content

Commit 6eedfbd

Browse files
committed
add Left#up and Right#up to upcast to Either
1 parent f4b7d43 commit 6eedfbd

File tree

2 files changed

+50
-6
lines changed

2 files changed

+50
-6
lines changed

src/library/scala/util/Either.scala

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,15 @@ sealed abstract class Either[+A, +B] extends Product with Serializable {
441441
final case class Left[+A, +B](value: A) extends Either[A, B] {
442442
def isLeft = true
443443
def isRight = false
444+
445+
/**
446+
* Upcasts this `Left[A, B]` to `Either[A, B1]`
447+
* {{{
448+
* Left(1).up[String] // Either[Int, String]
449+
* }}}
450+
*/
451+
def up[B1 >: B]: Either[A, B1] = this
452+
444453
}
445454

446455
/** The right side of the disjoint union, as opposed to the [[scala.util.Left]] side.
@@ -450,6 +459,15 @@ final case class Left[+A, +B](value: A) extends Either[A, B] {
450459
final case class Right[+A, +B](value: B) extends Either[A, B] {
451460
def isLeft = false
452461
def isRight = true
462+
463+
/**
464+
* Upcasts this `Right[A, B]` to `Either[A1, B]`
465+
* {{{
466+
* Right("1").up[Int] // Either[Int, String]
467+
* }}}
468+
*/
469+
def up[A1 >: A]: Either[A1, B] = this
470+
453471
}
454472

455473
object Either {
Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package scala.util
22

3-
import org.junit.{ Assert, Test }
3+
import org.junit.Assert._
4+
import org.junit.Test
45

56
class EitherTest {
67

@@ -13,9 +14,34 @@ class EitherTest {
1314
val flatrl: Either[String, Int] = rl.flatten
1415
val flatrr: Either[String, Int] = rr.flatten
1516

16-
Assert.assertEquals(Left("pancake"), flatl)
17-
Assert.assertEquals(Left("flounder"), flatrl)
18-
Assert.assertEquals(Right(7), flatrr)
19-
17+
assertEquals(Left("pancake"), flatl)
18+
assertEquals(Left("flounder"), flatrl)
19+
assertEquals(Right(7), flatrr)
2020
}
21-
}
21+
22+
@Test
23+
def testLeftUp: Unit = {
24+
25+
def rightSumOrLeftEmpty(l: List[Int]) =
26+
l.foldLeft(Left("empty").up[Int]) {
27+
case (Left(_), i) => Right(i)
28+
case (Right(s), i) => Right(s + i)
29+
}
30+
31+
assertEquals(rightSumOrLeftEmpty(List(1, 2, 3)), Right(6))
32+
assertEquals(rightSumOrLeftEmpty(Nil), Left("empty"))
33+
}
34+
35+
@Test
36+
def testRightUp: Unit = {
37+
38+
def leftSumOrRightEmpty(l: List[Int]) =
39+
l.foldLeft(Right("empty").up[Int]) {
40+
case (Right(_), i) => Left(i)
41+
case (Left(s), i) => Left(s + i)
42+
}
43+
44+
assertEquals(leftSumOrRightEmpty(List(1, 2, 3)), Left(6))
45+
assertEquals(leftSumOrRightEmpty(Nil), Right("empty"))
46+
}
47+
}

0 commit comments

Comments
 (0)