Skip to content

Commit 8a86ba8

Browse files
committed
arrow.kt catch
1 parent 81ecf76 commit 8a86ba8

File tree

1 file changed

+28
-0
lines changed
  • src/main/kotlin/com/hoc081098/kotlin_playground/arrowkt

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.hoc081098.kotlin_playground.arrowkt
2+
3+
import arrow.core.raise.Raise
4+
import arrow.core.raise.catch
5+
import arrow.core.raise.either
6+
7+
data class User(val id: Int, val name: String)
8+
sealed interface Error {
9+
data class UserNotFound(val id: Int) : Error
10+
}
11+
12+
fun findUserById(id: Int): User =
13+
throw NoSuchElementException("User'$id' not found")
14+
15+
context(Raise<Error.UserNotFound>) fun findUserByIdWithRaise(id: Int): User =
16+
catch(
17+
block = { findUserById(id) },
18+
catch = {
19+
if (it is NoSuchElementException)
20+
raise(Error.UserNotFound(id))
21+
else
22+
throw it
23+
}
24+
)
25+
26+
fun main() {
27+
println(either { findUserByIdWithRaise(1) })
28+
}

0 commit comments

Comments
 (0)