Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: contravariance for R, A in Effect, EagerEffect and in for *EffectScope #2722

Merged
merged 7 commits into from May 23, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions arrow-libs/core/arrow-core/build.gradle.kts
Expand Up @@ -40,3 +40,8 @@ kotlin {
}
}
}

// enables context receivers for Jvm Tests
tasks.named<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>("compileTestKotlinJvm") {
i-walker marked this conversation as resolved.
Show resolved Hide resolved
kotlinOptions.freeCompilerArgs += "-Xcontext-receivers"
}
@@ -0,0 +1,56 @@
package arrow.core.continuations

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.Dispatchers

sealed interface MyError
sealed interface SubError : MyError
sealed interface OtherError : MyError {
object Actual : OtherError
}

context(EffectScope<SubError>)
suspend fun subprogram(): Unit =
println("Hello SubProgram!")

context(EffectScope<OtherError>)
suspend fun otherprogram(): Unit =
println("Hello OtherProgram!")

context(EffectScope<OtherError>)
suspend fun fail(): MyResponse =
shift(OtherError.Actual)

fun main() =
runBlocking(Dispatchers.Default) {
effect<MyError, Unit> {
subprogram()
otherprogram()
fail()
}.fold(::println) { }
// Hello SubProgram!
// Hello OtherProgram!
// OtherError$Actual@7cd62f43
}

sealed interface MyResponse
object EmptyResponse : MyResponse
data class ErrorResponse(val error: Throwable) : MyResponse
data class BodyResponse(val body: String) : MyResponse

context(EffectScope<SubError>)
suspend fun respondWithBody(): BodyResponse =
BodyResponse("Hello Program!")

context(EffectScope<OtherError>)
suspend fun attemptOrError(): MyResponse =
ErrorResponse(RuntimeException("Oh no!"))

fun respond(): Effect<MyError, MyResponse> =
effect {
when (attemptOrError()) {
is BodyResponse -> respondWithBody()
EmptyResponse -> EmptyResponse
is ErrorResponse -> fail()
}
}