https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
arrow
  • d

    Dirk

    08/23/2022, 12:55 PM
    Hello, I get an error in interaction between Arrow and Ktor. In the route I use an HttpClient which is not recreated on request basis. The exception only occurs in case of error (server unreachable by HttpClient). In the good case, the method works as desired. Can anyone do anything with the error?
    s
    • 2
    • 4
  • r

    raulraja

    08/23/2022, 7:16 PM
    Hello everyone, just wanted to share the good news and give you peace of mind. You can expect our involvement with Arrow to continue and I hope we can bring more people and make the ecosystem bigger. 🙏 Thanks for your continuous support and making this community great! https://twitter.com/raulraja/status/1562153619079708672
  • j

    Jorge Bo

    08/25/2022, 8:53 PM
    Hi, i’m learning arrow and wanted to check if the following code is the correct way to add a branch in an either block. That if doesn’t look so functional to me..
    override suspend fun invoke(command: Command): Either<BusinessError, Unit> = 
            either {
                val responseOne = serviceOne.call(command.data.first).bind()
                val responseTwo = serviceTwo.call(command.data.second).bind()
        
                if (responseOne.amount > responseTwo.amount) {
                    serviceThree.call()
                }
            }
    e
    r
    • 3
    • 6
  • i

    Iurysza

    08/26/2022, 1:37 PM
    Hey everyone, I’ve just started using arrow in a personal project and I was looking to get some feedback on my first try of it:
    @Singleton
    class AuthUseCase @Inject constructor(
        private val networkDataSource: NetworkDataSource,
        private val storage: AuthStorage,
    ) {
    
        suspend fun refreshTokenIfNeeded(): Either<DomainError, Unit> = either {
            val token = storage.getToken().bind()
            ensure(token.expirationDate.isInTheFuture()) {
                TokenExpired
            }
        }.handleErrorWith { error ->
            when (error) {
                is TokenNotFound,
                TokenExpired,
                -> fetchNewTokenAndSaveIt()
                else -> error.left()
            }
        }
    
        private suspend fun fetchNewTokenAndSaveIt(): Either<DomainError, Unit> = either {
            networkDataSource.getAccessToken().bind()
        }.flatMap { (accessToken, expiresIn) ->
            catch {
                AuthToken(
                    accessToken,
                    expirationDate = nowPlusMillis(expiresIn)
                )
            }.mapLeft { InvalidExpirationDate }
        }.map { storage.putToken(it) }
    }
    Is the code above
    arrow
    idiomatic? Anything that can be improved or that is completely off? Thanks!
    q
    • 2
    • 4
  • d

    dimsuz

    08/26/2022, 4:33 PM
    Hi! I have a certain dificulty with optics which is illustrated by example:
    interface HasAge { val age: Int }
    
    @optics
    data class Form(
      override val age: Int
    ): HasAge {
      companion object
    }
    // is exported out of the current "module"
    val lens: Lens<HasAge, Int> = Form.age // compilation error
    
    // in another module
    fun transformAge(form: HasAge, lens: Lens<HasAge, Int>)
    Can i somehow generate lens so that it can be assignable in the
    val lens
    line? Very likely that all this trouble points to the wrong design on my part, but the thing is that full type information is lost between the modules, I cannot export full
    data class Form
    to be accessible to another module, all I've got is
    Any
    which I can cast to
    HasAge
    and then I thought I'd apply the lens (which also can be exported).
    a
    • 2
    • 5
  • t

    Tobias Hermann

    08/27/2022, 7:15 PM
    Hi. 🙂 I'm trying to find out, how to use arrow-kt to convert a function taking two parameters into a function taking a pair. I wrote this goofy
    tuplize
    function:
    fun foo(x: Int, y: Int) = 3 * x + 2 * y + 1
    
    fun <T, U, R> tuplize(f: (T, U) -> R): ((Pair<T, U>) -> R) = { (a, b): Pair<T, U> -> f(a, b) }
    
    val xs = listOf(Pair(1, 2), Pair(42, 23))
    
    val ys = xs.map(tuplize(::foo))
    It works, but I guess arrow-kt already has something nice build-in, and I just can't find it. Can somebody help me out?
    a
    • 2
    • 3
  • l

    Lawrence

    08/28/2022, 8:57 PM
    Hey all. I am trying to race calls to 2 APIs where I keep retrying it till I either get the proper data or till it times out. In case, I hit the timeout, I would like to return the list of
    Throwable
    that were returned while handling the API. I came up with this code not sure if this is the optimal way to do so:
    suspend fun scheduleCall(service: Service, handleError: (Throwable) -> Unit) =
        (Schedule.doWhile<Either<Throwable, Data>> { it.isEmpty() }
                .logOutput { it.mapLeft { throwable -> handleError(throwable) } })
            .repeat { service.call() }
    suspend fun callServices(
        a: Service,
        b: Service
    ): Either<List<Throwable>, String> {
      val errors = mutableListOf<Throwable>()
      val winner =
          raceN(
              <http://Dispatchers.IO|Dispatchers.IO>,
              { scheduleCall(a) { errors += it } },
              { scheduleCall(b) { errors += it } },
              { delay(60.seconds) })
      return when (winner) {
        is First -> "A".right()
        is Second -> "B".right()
        is Third -> errors.left()
      }
    }
    s
    • 2
    • 4
  • g

    Gavin Ray

    08/30/2022, 5:46 PM
    The note on this page says it was put into the
    arrow-meta
    repo, does anyone know whether this went anywhere? Would love to have proper pattern matching in Kotlin -- even Java has it now! 😅 https://mattmoore.io/kotlin-pattern-matching
    r
    m
    • 3
    • 4
  • j

    João Gabriel Zó

    08/30/2022, 9:50 PM
    I know this could be more of a general question, but maybe arrow users could give a little more context. I’m writing the first non-spring-arrow-using application in my company, trying to introduce them to a more functional way of doing things, specially with matters concerning error/exception handling. How could I write a good documentation explaining not only the application but also reinforcing the benefits of using Arrow.
    s
    • 2
    • 8
  • j

    Javier

    08/31/2022, 2:16 PM
    If Nel is not serializable you can create a custom serializer for it
    s
    b
    t
    • 4
    • 7
  • k

    Kev

    09/01/2022, 7:50 AM
    Hey, I’m trying to use the
    Either.resolve
    extension function that is commented as “resolving some suspended function” however, the function parameter is not of a suspended type. Would this be a problem with the docs, the implementation or my understanding? https://github.com/arrow-kt/arrow/blob/main/arrow-libs/core/arrow-core/src/commonMain/kotlin/arrow/core/Either.kt#L1175-L1199
    e
    p
    • 3
    • 6
  • g

    Gopal S Akshintala

    09/01/2022, 4:15 PM
    Hey 👋 is there an Open-Collective for Arrow library family to Sponsor? I couldn’t find any here: https://opencollective.com/search?q=arrow
    r
    • 2
    • 1
  • m

    mitch

    09/01/2022, 8:38 PM
    I was wondering if there are any new thoughts on “how to convert a
    List<Either<A,B>>
    to two separate lists of As and Bs in an arrow way”? That
    partitionEithers
    looks awesome and it’s nice that it works with any Foldable, but is a bit tough to grok. Anything new available in the last 3 years?
    r
    g
    • 3
    • 18
  • c

    carbaj0

    09/03/2022, 6:24 AM
    Lately I’ve been trying to create a small library that could be public. My question is the following: When you have a function with optional parameters (these parameters are lambdas), which is better to pass an empty lambda or create several functions that make use of all its parameters?
    s
    • 2
    • 2
  • f

    franztesca

    09/03/2022, 8:29 PM
    Ciao, I'm a FP and arrow newbie. I'm trying to follow the updates relative to the PR https://github.com/arrow-kt/arrow/pull/2797 and have a couple of questions: In Arrow 1 the short circuit (shift) is throwing a
    ControlThrowable
    (which is not a
    CancellationException
    ), in the PR with the inline fold the shift throws a
    ShiftCancellationException
    , which is a
    CancellationException
    ... Therefore Arrow 2 is going to have a different behavior when interacting with the Kotlin coroutines, as stated here (and the conclusion of that was "It seems that continuing to use
    ControlThrowable
    for shifting/short-circuiting is the best option.").
    Why have you chosen to use a
    CancellationException
    instead of
    ControlThrowable
    ? Question 2: It seems to me that the new solution (the inline fold and
    ShiftCancellationException
    implementing the short circuit) is much simpler than the one implemented using continuations. Why did you choose the continuation approach in the first place and is there any drawback with the simpler throw/catch
    ShiftCancellationException
    ? Thank you!
    s
    • 2
    • 1
  • a

    Alex Yordanov

    09/05/2022, 3:57 AM
    Howdy, could someone suggest a better way to wrap a
    callbackFlow
    in
    Either
    ? I came up with that but it looks kind of funky:
    val flow = callbackFlow<Unit> {
        delay(2000)
        cancel(CancellationException("Boom"))
    }
    
    Either.catch {
        flow
            .catch { throw RuntimeException(it.message) }
            .collect()
    }.mapLeft { it.message?.let { msg -> FlowError.Canceled(msg) } }
    s
    s
    • 3
    • 6
  • m

    Masrur Mirboboev

    09/05/2022, 8:15 PM
    Heyo, Is there a built in method to iterate over the list and collect all failures from all items of the iterable?
    traverse
    seems to short circuit on the first failure.
    q
    s
    s
    • 4
    • 5
  • l

    Lukasz Kalnik

    09/08/2022, 12:43 PM
    Is there an elegant way of integrating
    Either
    with other wrappers? I have a
    MutableStateFlow<Either<DataMissing, T>>
    and want to update it only if it's a `Right`:
    val automations: MutableStateFlow<Either<DataMissing, AutomationList>>
    
        private fun handleEvent(event: EntityModel) {
            if (event is AutomationUpdatePendingStateEvent) {
                automations.update { automationsEither ->
                    automationsEither.map { automations ->
                        automations.updateAutomationState(
                            automationId = event.automationId,
                            pendingState = event.deviceState,
                            provisioningComplete = event.provisioningComplete
                        )
                    }
                }
            }
        }
    s
    s
    • 3
    • 44
  • a

    Archie

    09/09/2022, 2:50 AM
    Hi very new in using Arrow. Was wondering how to handle scenario where I have two
    Either
    and both have to be
    right
    for me to do proper computation?
    y
    • 2
    • 3
  • s

    Stylianos Gakis

    09/09/2022, 9:22 AM
    I’ve caught myself do something like this:
    return either<Error, Unit> {
      parZip(
        { someComputation().toEither() },
        { someComputation().toEither() },
      ) { one, two ->
        one.bind()
        two.bind()
      }
    }
    When I simply want two things to run in parallel, get the structured concurrency guarantees of cancelling each other if one fails, and simply get an answer of it both succeeded or not. I feel like the parZip is kinda of redundant since I’m not combining the two results in any way, and could even move the
    bind()
    inside the two lambdas and then the trailing lambda is useless. Is there some other part of the arrow API that I’m missing, or might as well go with doing the
    async();async();awaitAll()
    dance myself?
    s
    • 2
    • 3
  • j

    Jorge Bo

    09/09/2022, 8:45 PM
    Hey, i’m having problems to understand where bind inside either block should be called, i realize that sometimes i forgot to call it and the code basically does not execute.
    q
    s
    • 3
    • 3
  • t

    thanh

    09/12/2022, 9:25 AM
    How can I
    mapLeft
    in the new
    EffectScope
    ?
    context(EffectScope<Throwable>)
    fun count(): Int = TODO()
    
    sealed interface DomainError
    
    context(EffectScope<DomainError>)
    fun logic(): Int {
      // I want to map Throwable to DomainError here
      return count()
    }
    s
    • 2
    • 22
  • f

    Fiouz

    09/13/2022, 5:53 AM
    are there specific OS, JDK, or IP stack requirements to build Arrow? I have failures on https://github.com/arrow-kt/arrow/blob/90f3c96d8ff2f8e54c1f63c4e9b6e79f9720c277/ar[…]/adapter/either/networkhandling/NetworkEitherCallAdapterTest.kt because it expects the cause to be ConnectException , but I get SocketException :
    java.lang.AssertionError: java.net.SocketException: Software caused connection abort: recv failed is of type java.net.SocketException but expected java.net.ConnectException
    s
    l
    • 3
    • 13
  • k

    Kristian Nedrevold

    09/13/2022, 6:40 PM
    Hey, what happens when you have code like
    fun foo(): Either<Err, Ok>
    val res = foo().map { bar(it) }.mapLeft { return it }
    and foo() is Err?
    q
    l
    o
    • 4
    • 10
  • g

    Gavin Ray

    09/16/2022, 9:16 PM
    With the 1.7.20-RC, the
    Inline classes with generic underlying type (experimental)
    feature can improve some wrapper classes in Arrow, right? In a few places in the source, I think I recall seeing
    data class Foo<T>(val value: T)
    s
    • 2
    • 10
  • g

    Gavin Ray

    09/16/2022, 9:17 PM
    (It would be nice if Kotlin had an equivalent to Java errorprone's
    .refaster
    for writing automated refactoring code to do stuff like this)
    s
    • 2
    • 1
  • n

    Neil Miller

    09/20/2022, 3:24 AM
    I'm looking at doing more work in Kotlin Multi-platfom. We've been using Vavr a lot, and Arrow is a natural replacement for a lot of that, but we'd really miss Vavr's true immutable collections. Is there any interest is a Kotlin port of Vavr's immutable collections becoming part of Arrow? (I'm aware of kotlinx.collections.immutable, but not a fan of some of the choices they've made)
    s
    s
    +2
    • 5
    • 15
  • r

    raulraja

    09/20/2022, 4:14 PM
    https://twitter.com/arrow_kt/status/1572209701097705473
    f
    a
    +2
    • 5
    • 6
  • v

    Ville Peurala

    09/21/2022, 6:44 AM
    Where has Functor disappeared from Arrow? In 0.12 it was there: https://arrow-kt.io/docs/0.12/arrow/typeclasses/functor/ How do I implement a Functor for my own type in 1.1.3?
    s
    • 2
    • 15
  • t

    Tower Guidev2

    09/21/2022, 1:15 PM
    Hi i require some guidance on how to deal with (e.g. catch) json parsing exceptions when making retrofit api calls using arrow retrofit apdapter
    • 1
    • 5
Powered by Linen
Title
t

Tower Guidev2

09/21/2022, 1:15 PM
Hi i require some guidance on how to deal with (e.g. catch) json parsing exceptions when making retrofit api calls using arrow retrofit apdapter
my calling code resembles this...
private suspend fun actualWork(): Either<Any, Any> = either {
    val networkData = repository.pharmaDocumentsSearch(options = mapOf("text" to "*", "limitation.count" to "100")).tapLeft { networkError -> consumeNetworkError(workerName, networkError) }.bind()
    Either.catch { repository.database.documentSearchItemDAO().insertAsync(manufacture(networkData)) }.tapLeft { databaseError -> consumeDatabaseError(workerName, databaseError) }.bind()
}
and my error processing function is
fun consumeNetworkError(caller: String, exception: CallError) {
    when (exception) {
        is HttpError -> doLogging { "$caller Network Http error :: ${exception.code} ${exception.message} ${exception.body}" }
        is IOError -> doLogging(exception.cause) { "$caller Network IO error" }
        is UnexpectedCallError -> doLogging(exception.cause) { "$caller Unexpected Network error" }
    }
}
which all works really nicely
however when a json parsing exception occurs i do not log any errors my
actualWork
function fails silently
here is the repositiry function
override suspend fun pharmaDocumentsSearch(headers: Map<String, String>, options: Map<String, String>): Either<CallError, DocumentsSearch> =
    withContext(NETWORK) { service.pharmaDocumentsSearch(headers = HEADERS, options) }
so i need to "wrap" the network call in an outer
Either.catch { }
View count: 6