https://kotlinlang.org logo
Docs
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
  • o

    Oliver Eisenbarth

    09/23/2022, 6:03 AM
    Hello, I have a set of functions that validate some object. I zip those to get a Validated and use them in an either block. Now I am wondering, what the most idiomatic way to enabling 1-n of those functions via a configuration file would be. In the end, I need to get from a list of Booleans (validationX enabled?) to a list of validation functions, that need to get zipped for a result ...writing it in pseudocode...Either<InvalidFoo(reasons: Nel<Plausibility>>, ValidFoo>. Any ideas?
    s
    s
    • 3
    • 9
  • a

    alexey_gusev

    09/23/2022, 12:20 PM
    Hello, Could someone with setting up Arrow analysis plugin with Android? I’m following https://arrow-kt.io/docs/meta/analysis/ but I get the error when building:
    Configuration with name 'implementation' not found.
    Do I miss some dependency as it seems?
    a
    r
    • 3
    • 12
  • j

    João Gabriel Zó

    09/23/2022, 5:02 PM
    I have a return type
    Either<Error, List<A>>
    is there a way to map directly into the list without having to
    either.map{ it.map { f } }
    ?
    s
    • 2
    • 2
  • o

    Oliver Eisenbarth

    09/26/2022, 9:31 AM
    Hello! I am wondering what happened to [at]product and the toHList(), isn't that part of Arrow anymore?
    r
    • 2
    • 3
  • m

    mitch

    09/26/2022, 2:34 PM
    heya all, it seems like the latest arrow was missing a few utilities for
    List<T> -> Option<NonEmptyList<T>>
    ? was it missed? Context, I found out
    NonEmptyList.fromList
    is now deprecated in favour of nullable types
    list.toNonEmptyListOrNull()
    which is quite verbose. In our kotlin projects, we favour
    Option<T>
    and we don’t use nullable types, hence now we will need to do a
    list.toNonEmptyListOrNull().toOption()
    which is even more verbose.. I wonder if there’s any objections if I raise a PR to introduce
    list.toNonEmptyListOrNone()
    ? or a shorter one such as
    list.toNelOrNone()
    r
    s
    +2
    • 5
    • 8
  • w

    Wilerson Oliveira

    09/27/2022, 2:31 PM
    val bar = it.invoke(command) as E
    I would guess this casting is the culprit. Wouldn’t
    val bar = it.invoke(command).bind()
    work?
    s
    e
    • 3
    • 22
  • s

    simon.vergauwen

    09/29/2022, 10:23 AM
    https://imgflip.com/i/6v3rs0 Evolving the Either API for Arrow 2.0, we want to reduce the API surface so that we can offer uniform APIs and simply the learning curve for everyone. https://github.com/arrow-kt/arrow/pull/2830
    r
    t
    s
    • 4
    • 8
  • s

    Stylianos Gakis

    09/30/2022, 11:43 AM
    Going to arrow-kt.io, in specifically the page which shows the API for arrow core here (Don’t think the fact that it’s a reference to a specific method matters in this case) is literally nuking my Chrome browser, it becomes unresponsive for at least half a minute after trying to close the tab down 😅 And I am not even on a low end computer. I recently wrote a SOF comment with a link there here and I am afraid I’m gonna nuke their computer for whoever clicks it 😂 Is this something on your end or how the web page is generated or possibly only I am experiencing it? Asking here before I make a GH issue just to see if it’s only me who experiences it
    r
    s
    • 3
    • 8
  • j

    João Gabriel Zó

    10/03/2022, 3:06 PM
    I’m looking for an elegant way to log each case of an Either on my controller without going
    when (either) {}
    everywhere. Any ideas?
    w
    s
    • 3
    • 2
  • w

    Wesley Hartford

    10/05/2022, 5:16 PM
    I'm just starting to work with effects. It seems like the following code should be allowed:
    sealed interface LeftResult
    sealed interface DatabaseLeftResult: LeftResult
    sealed interface ApiLeftResult: LeftResult
    
    fun queryDatabase() = effect<DatabaseLeftResult, Int> { 42 }
    fun submitNumber(number: Int) = effect<ApiLeftResult, Unit> { println(number) }
    fun queryAndSubmit() = effect<LeftResult, Unit> {
      val number = queryDatabase().bind()
      submitNumber(number).bind()
    }
    However, both of the
    bind
    calls in
    queryAndSubmit
    result in an unresolved reference error. If I make
    queryDatabase
    and
    submitNumber
    use
    LeftResult
    on the left rather than the sub-interface, the code compiles. I can also change the
    bind
    call to
    .toEither().bind()
    and the code compiles. Shouldn't my original code compile though?
    s
    • 2
    • 3
  • l

    Lukasz Kalnik

    10/06/2022, 3:03 PM
    I'm running into a weird problem recently in Android Studio Electric Eel. All of a sudden, the
    bind()
    function of the
    either {}
    scope stops being recognized (although it just worked a few moments before and there were no changes in the code):
    Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
    public open suspend fun <B> Either<CallError, TypeVariable(B)>.bind(): TypeVariable(B) defined in arrow.core.continuations.EffectScope
    public open suspend fun <B> Option<TypeVariable(B)>.bind(shift: () -> CallError): TypeVariable(B) defined in arrow.core.continuations.EffectScope
    public open suspend fun <B> Validated<CallError, TypeVariable(B)>.bind(): TypeVariable(B) defined in arrow.core.continuations.EffectScope
    public open suspend fun <B> EagerEffect<CallError, TypeVariable(B)>.bind(): TypeVariable(B) defined in arrow.core.continuations.EffectScope
    public open suspend fun <B> Effect<CallError, TypeVariable(B)>.bind(): TypeVariable(B) defined in arrow.core.continuations.EffectScope
    public open suspend fun <B> Result<TypeVariable(B)>.bind(transform: (Throwable) -> CallError): TypeVariable(B) defined in arrow.core.continuations.EffectScope
    s
    s
    • 3
    • 21
  • k

    Kristian Nedrevold

    10/07/2022, 12:38 AM
    What is a the idiomatic way to use either in a function that deals with nullables. I tried making an example. The point is that the error correctly shows where the function failed. This works, but it's kinda hard to read?
    fun foo(): String? = if ((0..1).random() == 1) "Hello World" else null
        fun bar(s: String): String? = if ((0..1).random() == 1) s else null
    
        fun maybe(foo: () -> String?, bar: (input: String) -> String?): Either<Err, String> =
            foo()?.let { first ->
                bar(first)?.let { second ->
                    Either.Right(second)
                } ?: Either.Left(Err("Could not find second"))
            } ?: Either.Left(Err("Could not find first"))
    
    
        maybe(::foo, ::bar)
    c
    s
    p
    • 4
    • 8
  • j

    John Herrlin

    10/10/2022, 8:04 AM
    Hey! I have two "remote" calls. I want
    product
    to be called first and if that succeeds
    add
    should be called. But in the following code
    product
    and
    add
    is called concurrently. How can I make them not concurrent? 😃
    import java.io.IOException
    import arrow.core.computations.either
    import arrow.core.Either
    import arrow.core.Either.Left
    import arrow.core.Either.Right
    import arrow.core.getOrHandle
    
    data class Error(val errorString: String, val exception: Exception?)
    
    fun <A> remote(f: () -> A): A = if (Math.random() > 0.2) f() else throw IOException("boom!")
    
    fun <A> trap(errorString: String, f: () -> A): Either<Error, A> =
        try { Right(f()) }
        catch (e: Exception) { Left(Error(errorString, e)) }
    
    fun multiply(a: Int, b: Int): Either<Error, Int> = trap("multiplication failed") { remote { a * b } }
    
    fun add(a: Int, b: Int): Either<Error, Int> = trap("addition failed") { remote { a + b } }
    
    // If fetching `product` is failing `sum` should not be called at all.
    suspend fun calculate(a: Int, b: Int): Either<Error, Int> =
        either<Error, Int> {
            val product = multiply(a, b).bind()
            val sum = add(a, b).bind()
            sum }
    
    suspend fun main() {
        println(calculate(2, 10).getOrHandle { it.errorString })
        println(calculate(2, 10).getOrHandle { it.errorString })
    }
    s
    • 2
    • 4
  • m

    Marc Plano-Lesay

    10/13/2022, 5:16 AM
    Hello! Looks like there's a bit of an issue with the docs, e.g. https://arrow-kt.io/docs/apidocs/index.html - the left menu is missing a lot of things
    s
    • 2
    • 1
  • l

    Lukáš Kúšik

    10/13/2022, 7:58 AM
    Hi, I'm encountering this issue https://github.com/arrow-kt/arrow/issues/2725 with Arrow Optics in a Kotlin Multiplatform project. The NPE points to this line of code https://github.com/arrow-kt/arrow/blob/ebd3406effb503ca1909e3b7110232ef85a9ba06/ar[…]ugin/src/main/kotlin/arrow/optics/plugin/internals/processor.kt I have found that it has already been fixed in the
    removed-in-arrow-2
    branch in this commit: https://github.com/arrow-kt/arrow/commit/62044120c483b01304819900a5e4cd8b4f1e8ece Would it be possible to back-port this fix to the current version?
    s
    • 2
    • 5
  • j

    Jakub Gwóźdź

    10/13/2022, 9:48 AM
    Hi there. I’m using
    ValidatedNel
    to validate and accumulate potential errors when converting objects from one domain to another. Thing is that these objects (deserialized from rest endpoints) have like 20+ fields, which requires me to write custom large
    .zip
    extensions, since the library provides arity only up to 10. This is not only inconvenient, but also simply smelly. Is there any better way (or some kind of best practice) to perform validations/conversions on such large number of parameters?
    s
    • 2
    • 1
  • k

    Kristian Nedrevold

    10/13/2022, 9:05 PM
    Hi, I am learning how to work with Validated as it seems very nice, I have also been playing around with context receivers. Does this look good?
    data class Ssn(val ssn: String) {
        companion object {
    
            suspend fun create(ssn: String): ValidatedNel<ValidationError, Ssn> = Validated.fromEither(
                either {
                    val validLengthAndAllNumerical = validateLengthAndAllNumerical(ssn).bind()
                    Ssn(validateControlNumbers(validLengthAndAllNumerical).bind())
                })
    
    
            private fun validateLengthAndAllNumerical(ssn: String): ValidatedNel<ValidationError, String> = with(ssn) {
                    length().zip(allNumbers()) { _, _-> ssn }
                }
    
            context(String)
            private fun length(): ValidatedNel<ValidationError, Unit> =
                if (length == 11) Unit.valid()
                else ValidationError.IncorrectLength.invalidNel()
    
            context(String)
            private fun allNumbers(): ValidatedNel<ValidationError, Unit> =
                if (filter { it.isDigit() }.length == length) Unit.valid()
                else ValidationError.NotAllDigits.invalidNel()
    
            private fun validateControlNumbers(ssn: String): ValidatedNel<ValidationError, String> {
                val firstCtrl = listOf(3, 7, 6, 1, 8, 9, 4, 5, 2, 1)
                val secondCtrl = listOf(5, 4, 3, 2, 7, 6, 5, 4, 3, 2, 1)
                val ssnNumeric = ssn.map { it.digitToInt() }
    
                val firstValid = ssnNumeric.dropLast(1).reduceIndexed { index, acc, i ->
                    acc + (i * firstCtrl[index]) } % 11 == 0
    
                val secondValid = ssnNumeric.reduceIndexed { index, acc, i ->
                    acc + (i * secondCtrl[index]) } % 11 == 0
    
                return if (firstValid && secondValid) ssn.valid()
                else ValidationError.RuleViolation.invalidNel()
            }
        }
    }
    
    sealed class ValidationError {
        data object Error: ValidationError()
        data object IncorrectLength: ValidationError()
        data object NotAllDigits: ValidationError()
        data object RuleViolation: ValidationError()
    }
    m
    s
    • 3
    • 3
  • j

    Jakub Gwóźdź

    10/14/2022, 7:36 AM
    Hi, is there any “flatMap-ish” equivalent for
    Validated.zip(...)
    ? Where the last parameter (combining function) also returns ValidatedNel, not the resulting value?
    s
    • 2
    • 2
  • j

    Jakub Gwóźdź

    10/14/2022, 7:37 AM
    And second question: I heard that
    Validated
    is going away in favour of
    Either
    . Are there any tutorials how to perform error-accumulating validations with
    Either
    ?
    s
    • 2
    • 1
  • d

    Davide Giuseppe Farella

    10/15/2022, 1:28 PM
    Good morning. I have a function that accepts a lambda that returns
    Either<NetworkError, T>
    Something like
    fun <T : Any> MyFun(
        ...
        fetch: suspend () -> Either<NetworkError, T>,
        ...
    ): Flow<Either<DataError, T>>
    Now I have a new use case, as I started supporting a guest mode, so besides
    NetworkError
    and
    T
    I need something to represent a case when the user is not logged in, which I don’t want to be part of either of the 2 mentioned. What would you suggest to use instead of
    Either<NetworkError, T>
    ? (
    Skipped
    = call didn’t happen ) Here are some solutions that I thought of, but dunno which one would be nicer, or if there are other solutions: •
    Either<Either<NetworkError, Skipped>, T>
    this would be the easier one to achieve/refactor; not sure how nice it would be to nest 2
    Either
    •
    Either<NetworkResult, T>
    sealed interface NetworkResult {
      object Skipped : NetworkResult
      data class Error(val networkError: NetworkError)
    }
    • Replace
    Either
    with a sealed interface, like following
    sealed interface NetworkResult<T> {
      object Skipped : NetworkResult<Nothing>
      data class Error<Nothing>(val networkError: NetworkError)
      data class Data(val data: T)
    }
    The last solution is probably the cleanest, but I’d lose the
    Either
    operators that I’m currently using, like
    tap
    ,
    fold
    ,
    bind
    , etc The second one would be my preferred
    s
    • 2
    • 3
  • n

    Norbi

    10/16/2022, 7:44 AM
    Is Arrow Meta unmaintained? I've just checked and there have been no commits for months... Thanks.
    m
    r
    • 3
    • 3
  • c

    carbaj0

    10/17/2022, 4:25 AM
    i´m trying Arrow Optics, and i have a nullable field, but I can´t modify it with a null value, I have to make the field
    Option<S>
    Since we are kotlin syntax friends, i wonder if isn´t possible to set/modify nullable types
    s
    • 2
    • 2
  • c

    CLOVIS

    10/18/2022, 1:36 PM
    Is there a good explanation available of how the
    bind
    abstraction is implemented? I'd like to adapt it to a StateFlow (essentially the same as Either's with success and error, but the value changes over time).
    s
    r
    • 3
    • 17
  • l

    Lukasz Kalnik

    10/19/2022, 12:11 PM
    What is the
    arrow-fx-stm
    dependency?
    s
    • 2
    • 38
  • p

    pakoito

    10/19/2022, 3:55 PM
    Is top-level Zip for Validated still around?
  • p

    pakoito

    10/19/2022, 3:55 PM
    or only the extension version?
  • s

    simon.vergauwen

    10/19/2022, 4:09 PM
    Only as top-level extension.
  • s

    Shabinder Singh

    10/19/2022, 6:46 PM
    How can i convert a
    List<Either<A,B>>
    TO
    Either<List<A>,List<B>>
    OR
    ValidaterNel<A,List<B>>
    basically it iterates over either and collect both errors and success, •
    .sequence
    shortCircuits
    which isnt wanted here*,* •
    .traverse {}
    is there but I thought there would a extension function for above as its a common useCase I guess, is there an extension for above ?
    s
    r
    • 3
    • 6
  • o

    okarm

    10/20/2022, 5:43 PM
    Which is the correct ordering? Does it matter? 1.
    either
    inside
    withContext
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
      either {
        // Code that uses all of shift, bind,
        // and currentCoroutineContext().ensureActive()
      }
    }
    2.
    withContext
    inside
    either
    either {
      withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        // Code that uses all of shift, bind,
        // and currentCoroutineContext().ensureActive()
      }
    }
    p
    r
    s
    • 4
    • 4
  • g

    gabib

    10/24/2022, 1:40 PM
    Hi everyone, here’s the link to my talk about fp in Kotlin with Arrow from VoxxedDays. [

    https://youtu.be/BIPG5ooWMJM▾

    ]. I hope you find it useful.
    s
    • 2
    • 1
Powered by Linen
Title
g

gabib

10/24/2022, 1:40 PM
Hi everyone, here’s the link to my talk about fp in Kotlin with Arrow from VoxxedDays. [

https://youtu.be/BIPG5ooWMJM▾

]. I hope you find it useful.
s

Stylianos Gakis

11/11/2022, 9:23 PM
Finally got some time to watch this. Super nice talk, I loved your efforts to introduce the
context()
feature to the talk. Only makes me more eager to see it become available sometimes soon, in KMP too!
View count: 4