Skip to content

Commit

Permalink
Impl : Impl flatmap
Browse files Browse the repository at this point in the history
  • Loading branch information
myeonginwoo committed Dec 28, 2016
1 parent 9c7ea84 commit 216e851
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 1 deletion.
4 changes: 4 additions & 0 deletions Either/src/main/kotlin/LeftProjection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,8 @@ class LeftProjection<out L, out R>(val value: L) {
fun exists(f: (L) -> Boolean): Boolean {
return f(value)
}

fun <X, R1> flatMap(f: (L) -> Either<X, R1>): Either<X, R1> {
return f(value)
}
}
4 changes: 4 additions & 0 deletions Either/src/main/kotlin/RightProjection.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,8 @@ class RightProjection<out L, out R>(val value: R) {
fun exists(f: (R) -> Boolean): Boolean {
return f(value)
}

fun <L1, X> flatMap(f: (R) -> Either<L1, X>): Either<L1, X> {
return f(value)
}
}
10 changes: 9 additions & 1 deletion Either/src/test/kotlin/EitherTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class EitherTest {
assertEquals(rightEither.fold({ "Left is $it" }, { it * 3 }), 18)
}

@Test fun existsTesT() {
@Test fun existsTest() {
val leftEither: Either<String, Int> = Left("test")
assertEquals(leftEither.left?.exists { it.length == 4 }, true)
assertEquals(leftEither.left?.exists { it.length > 4 }, false)
Expand All @@ -84,4 +84,12 @@ class EitherTest {
assertEquals(rightEither.right?.exists { it > 5 }, true)
assertEquals(rightEither.right?.exists { it < 5 }, false)
}

@Test fun flatMapTest() {
val leftEither: Either<String, Int> = Left("test")
assertEquals(leftEither.left?.flatMap { Left<Int, Long>(3) }?.left?.get, 3)

val rightEither: Either<String, Int> = Right(6)
assertEquals(rightEither.right?.flatMap { Right<Int, String>("test") }?.right?.get, "test")
}
}
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,12 @@ val rightEither: Either<String, Int> = Right(6)
assertEquals(rightEither.right?.exists { it > 5 }, true)
assertEquals(rightEither.right?.exists { it < 5 }, false)
```

flatmap
```kotlin
val leftEither: Either<String, Int> = Left("test")
assertEquals(leftEither.left?.flatMap { Left<Int, Long>(3) }?.left?.get, 3)

val rightEither: Either<String, Int> = Right(6)
assertEquals(rightEither.right?.flatMap { Right<Int, String>("test") }?.right?.get, "test")
```

0 comments on commit 216e851

Please sign in to comment.