Skip to content

Commit

Permalink
Merge pull request #5 from myeonginwoo/fold
Browse files Browse the repository at this point in the history
impl fold
  • Loading branch information
myeonginwoo authored Dec 28, 2016
2 parents ad9d607 + 6a85aaa commit d616024
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
11 changes: 9 additions & 2 deletions Either/src/main/kotlin/Either.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,24 @@ sealed class Either<L, R> {
var left: LeftProjection<L, Nothing>? = null
var right: RightProjection<Nothing, R>? = null

class Left<L, R>(value: L) : Either<L, R>() {
class Left<L, R>(val value: L) : Either<L, R>() {
init {
isLeft = true
left = LeftProjection(value)
}
}

class Right<L, R>(value: R) : Either<L, R>() {
class Right<L, R>(val value: R) : Either<L, R>() {
init {
isRight = true
right = RightProjection(value)
}
}

fun <X> fold(fLeft: (L) -> X, fRight: (R) -> X): X {
return when (this) {
is Left -> fLeft(value)
is Right -> fRight(value)
}
}
}
16 changes: 12 additions & 4 deletions Either/src/test/kotlin/EitherTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ import org.junit.Test
class EitherTest {

@Test fun leftTest() {
val eitherLeft: Either<String, Int> = Left("test")
assertEquals("test", eitherLeft.left?.get)
assertEquals(true, eitherLeft.isLeft)
assertEquals(false, eitherLeft.isRight)
val leftEither: Either<String, Int> = Left("test")
assertEquals("test", leftEither.left?.get)
assertEquals(true, leftEither.isLeft)
assertEquals(false, leftEither.isRight)
}

@Test fun rightTest() {
Expand Down Expand Up @@ -66,4 +66,12 @@ class EitherTest {
assertEquals(either.right?.filter { it < 100 }, null)
assertEquals(either.right?.filter { it < 100 } ?: -1, -1)
}

@Test fun foldTest() {
val leftEither: Either<String, Int> = Left("test")
assertEquals(leftEither.fold({ "Left is $it" }, { it * 3 }), "Left is test")

val rightEither: Either<String, Int> = Right(6)
assertEquals(rightEither.fold({ "Left is $it" }, { it * 3 }), 18)
}
}

0 comments on commit d616024

Please sign in to comment.