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
  • c

    Cody Mikol

    09/21/2021, 2:13 PM
    What is the correct way to create a semigroup for
    Nel
    ? I’m doing something along the lines of
    list.parTraverseValidated(Nel.semigroup(), ::foobar)
    but this is not correct
    s
    • 2
    • 2
  • s

    Scott Christopher

    09/22/2021, 2:26 AM
    It seems as though the
    Queue
    type no longer exists in Arrow (presumably when
    IO
    went away?). I was looking to build a simple rate limiter using the bounded queue and
    Schedule
    if anyone has any suggestions for alternatives.
    s
    • 2
    • 3
  • b

    Benoît

    09/22/2021, 10:10 AM
    Hey guys, sorry this question might have been asked a few times already, but what’s the best way to learn arrow for someone that knows basic FP concepts?
    p
    • 2
    • 9
  • j

    jean

    09/23/2021, 7:51 AM
    What’s the best way to transform a
    List<Either<Error, Id>>
    to a
    Either<Error, List<Id>>
    ? I want a
    Either.Left
    return as soon as possible, not a list of all result eventually containing errors. Either an error immediately when something fails or a list of valid result
    s
    • 2
    • 8
  • i

    ivanmorgillo

    09/23/2021, 9:17 AM
    Shameless plug: we had a nice conversation with @pablisco and @seb about Arrow yesterday on Code With The Italians
    🙌 5
    :oh-yeah: 2
    p
    c
    • 3
    • 8
  • l

    Leo Laudouard

    09/23/2021, 10:30 AM
    Hi, Ktor http client, with CIO as engine configured with a request timeout (15 seconds by default), can throw a
    TimeoutCancellationException
    , which is a
    CancellationException
    . Hence, when using
    Either.catch
    to make a request, the exception is considered 'fatal', since
    793a51edce
    , and re-thrown. My question is, why is this considered fatal ? Thanks !
    s
    r
    • 3
    • 15
  • m

    Morten Andersen-Gott

    09/23/2021, 12:26 PM
    Hi. Just wanted to check if adding a method for combining validated instances has been considered? In cats there is a method called
    andThen
    which would be nice to have in arrow. Currently one can achieve something functionally equal with
    withEither
    like this:
    Validated.catch { "0".toInt() }.toValidatedNel().withEither { it.flatMap { Either.catch { 1 / it } }
    however going through an either instance feels unnecessary when one is still operating on validations. So perhaps something like this:
    fun <E,A, B> Validated<E, A>.andThen(f: (A) -> Validated<E, B>) :Validated<E, B> {
      return when(this){
        is Valid -> f(value)
        is Invalid -> this
      }
    }
    
    Validated.catch { "0".toInt() }.toValidatedNel().andThen { Validated.catch { 1/it } }
    Example is a simple, but it is quite useful when you want to do input validation first, and then if valid continue with more advanced validation rules
    s
    j
    • 3
    • 15
  • p

    Pratik Tandel

    09/24/2021, 4:22 AM
    is it possible to provide async versions of
    .map
    /
    .flatMap
    from arrow? right now it seems i will have to write extension functions that do something similar
    c
    s
    • 3
    • 15
  • p

    Pratik Tandel

    09/24/2021, 6:58 AM
    i had another question, how can i convert a List<ValidatedNel<Error, Result>> into
    ValidatedNel<Error, List<Result>>
    — basically i’d like to aggregate all errors whenever it failed
    s
    • 2
    • 21
  • l

    Luke

    09/24/2021, 9:19 PM
    I'm working with
    @optics
    to modify a
    data class
    . Let's say I have a
    data class Foo(val list: List<Bar>)
    , is there an operator to modify the only element in the list that matches a predicate?
    s
    • 2
    • 4
  • g

    gammax

    09/27/2021, 3:24 PM
    Thanks for sharing @stojan 🙏 Just came here to x-post from #feed https://kotlinlang.slack.com/archives/C0BJ0GTE2/p1632756199232400
    🎉 3
    r
    s
    s
    • 4
    • 7
  • m

    Morten Andersen-Gott

    09/27/2021, 7:04 PM
    Working on a PR and just about to push it, but not getting the site to build. Want to check that the tiny sample I’ve added to the doc looks ok. Getting
    arrow/arrow-site/vendor/bundle/ruby/3.0.0/gems/kramdown-1.17.0/lib/kramdown/parser/html.rb:10:in `require': cannot load such file -- rexml/parsers/baseparser (LoadError)
    Is there an easy fix? Not really well versed in gems and jekyll
    v
    p
    • 3
    • 3
  • d

    dnowak

    09/27/2021, 9:38 PM
    Hi, is there a support in Arrow for transforming: •
    () -> Either<Failure, Result>
    and •
    (Failure) -> Error
    to
    () -> Either<Error, Result
    . All I want to do is to “decorate” a function returning
    Either
    with error mapping.
    s
    • 2
    • 7
  • p

    pakoito

    09/28/2021, 1:59 PM
    In 1.0.0 is there a set of functions to partially apply multiple parameters?
    s
    • 2
    • 2
  • b

    benkuly

    09/28/2021, 7:05 PM
    Can Schedule be used to do the following: Do a job forever, but with an exponential backoff limited to 5min, which gets reset, when the job succeeds.
    j
    • 2
    • 2
  • e

    Eric

    09/29/2021, 5:15 PM
    I’m looking to transform a
    List<Validated<Foo, Unit>>
    to a single
    Validated<Bar, Unit>
    . I’m having trouble figuring it out. This works:
    val failed = values().map {
        it.validate(vehicleSettingEntity, states) // a Validated<ValidationError, Unit>
    }.filterIsInstance<Validated.Invalid<ValidationError>>().map { it.value }
    return when {
        failed.isEmpty() -> Unit.valid()
        else -> ValidationResult(failed).invalid()
    }
    But it feels like some sort of
    fold
    might be better here. Can anyone provide a little guidance?
    g
    j
    m
    • 4
    • 16
  • s

    soulbeaver

    09/30/2021, 12:15 PM
    Hey everyone, I'm currently trying to validate a series of sub-objects and then create a domain object out of it. What I'd like to implement is something akin to this
    personalData.validate().zip(
        Semigroup.nonEmptyList<ValidationError>(),
        taxData.validate(),
        productData.validate()
    ) { personData, taxData, productData -> Person(...) }
    However, all of the sub-objects have a different type: •
    personalData.validate() -> ValidatedNel<ValidationError, PersonalData>
    •
    taxData.validate() -> ValidatedNel<ValidationError, TaxData>
    Which means that instead of the above I'm currently doing a bunch of manual checks like so:
    val validatedPersonalData = when (val result = personalData.validate()) {
        is Valid -> result.value
        is Invalid -> validationErrors.addAll(result.value)
    }
    Over and over again until finally
    return if (validationErrors.isNotEmpty()) 
        validationErrors.invalidNel()
    else
        Person(validatedPersonalData, validatedTaxData, validatedProductData)
    Is there a better way of doing this?
    m
    • 2
    • 4
  • j

    julian

    09/30/2021, 8:15 PM
    It seems that now that Kotlin has sealed interfaces, it's preferable to use that than the coproduct datatype. Is that right? Are there any use-cases where coproduct would be the better choice?
    • 1
    • 1
  • j

    jean

    10/04/2021, 6:41 AM
    I’m trying to build an object composed of other dependencies, each dependency is obtained through a function returning
    Either<Error, x>
    , I got it too work but the code is rather cumbersome and difficult for anyone else to figure out quickly. This is a simplified version, but it works the same way :
    class A
    class B
    class C(
        val val1: String,
        val val2: String,
        val val3: String,
        val a: A,
        val b: B,
    )
    
    fun getA(val1: String): Either<Exception, A> = Either.Right(A())
    fun getB(val1: String): Either<Exception, B> = Either.Right(B())
    fun getCs(): Either<Exception, List<CBuilder>> = Either.Right(listOf(CBuilder("val1", "val2", "val3")))
    
    class CBuilder(
        val val1: String,
        val val2: String,
        val val3: String,
    )
    
    class EitherTest {
    
        @Test
        fun buildC() {
            getCs().flatMap { builders ->
                builders.map { builder ->
                    getA(builder.val1).flatMap { a ->
                        getB(builder.val1).map { b ->
                            C(builder.val1, builder.val2, builder.val3, a, b)
                        }
                    }
                }.sequenceEither()
            }
        }
    }
    Is there a way to simplify the two first
    map
    in one operator, and is there a way to avoid consequent nesting of
    map
    and
    flatmap
    ?
    s
    • 2
    • 4
  • c

    Cody Mikol

    10/05/2021, 2:51 AM
    Why does
    bifoldLeft
    have
    left
    in its name? It seems similar to
    fold
    with the addition of an extra initial property passed in to both the left and right lambdas. Would it make more sense for this to just be named
    bifold
    ?
    y
    • 2
    • 1
  • m

    Mickey Donaghy

    10/05/2021, 7:47 AM
    what's the equivalent of / replacement for
    WriterT
    these days? I want to use Either-like and Writer-like effects together
    👍 1
    s
    r
    j
    • 4
    • 14
  • a

    Alexander Levin

    10/05/2021, 6:15 PM
    Hi. I have couple of questions, mostly about "why something exists" and "why something is written that way" • Is there any use for
    Const
    assuming we don't have HKT simulation anymore? • Same question for
    widen
    (code examples seems to be working just fine without
    widen
    call) • Is there a reason to implement most functions inside of Either/Validated/etc or is it just the matter of preference? (I think standard library usually extract non-essential functions as extensions as much as it's possible considering interop) • Is there any code examples about using Arrow with any popular framework/library like Ktor or Spring? • What's the usage of
    Endo
    ? (didn't really find it in the repo)
    s
    • 2
    • 9
  • n

    niltsiar

    10/06/2021, 8:24 AM
    I've seen that Arrow 1.0.0 is now multiplatform, is it possible to use it with Kotlin/Native for iOS targets?
    p
    • 2
    • 3
  • n

    Nathan Bedell

    10/06/2021, 3:27 PM
    Hey all, I was wondering: Has anyone attempted to write a monad "effect" implementation for the
    Sequence
    monad (which I think would be similar to the List monad in Haskell), or any other similar non-deterministic monad using Arrow-style comprehension notation using coroutines? I know there are examples of "result type" comprehensions in arrow core (e.x.
    Either
    ), and I've been able on my own to figure out how to build a monad comprehension syntax for a
    ReaderT IO
    -like monad (this was actually pretty easy) -- but I can't for the life of me figure out how to encode a non-deterministic monad like
    Sequence
    using the methods of Arrow. Has anyone attempted this, or have any working examples? As I understand, the problem is basically to encode the monad as a sub-monad of the continuation monad (i.e the whole "continuations are the mother of all monads" thing) -- but I'm not experienced enough with continuations be able to grok that yet.
    j
    • 2
    • 7
  • c

    Connor Ford

    10/14/2021, 2:17 PM
    I'm following this article on applicatives and it looks like the api for
    Either
    has changed as
    ap
    is no longer resolved in this statement:
    location.ap(name.map(action))
    where
    location
    and
    name
    are both of type
    Either<String, String>
    and
    action
    is
    (String) -> (String) -> String
    . How can I find out what the updated sytnax should be?
    p
    • 2
    • 2
  • p

    Peter

    10/14/2021, 7:06 PM
    wondering if anyone have some input on a broader functional design question. is there a good way to group functions as dependencies (if that’s even a good way to think about it), simple example of a data store:
    fun saveSession(session: Session): Either<Throwable, Unit>
    fun getSession(id: SessionID): Either<Throwable, Session>
    for a specific implementation (Redis vs Relational vs mock) with additional dependencies:
    fun saveSession(connection: RedisConnection, session: Session): Either<Throwable, Unit>
    fun getSession(connection: ResdisConnection, id: SessionID): Either<Throwable, Session>
    this prevents grouping functions as an interface, even if using partial functions (i think) or using an interface OO-style:
    class RedisSessionManager(connection: RedisConnection): SessionManager {
    fun saveSession(session: Session): Either<Throwable, Unit>
    fun getSession(id: SessionID): Either<Throwable, Session>
    }
    side effects aside, no longer pure with the global external dependency Reader monad perhaps? not sure one ever gets away from the external implementation specific dependency (eg: connection), what approaches have you taken?
    n
    r
    p
    • 4
    • 21
  • c

    conner

    10/15/2021, 5:45 PM
    is this an idiomatic way to use
    ValidatedNel
    ?
    fun buildMyObjectObject(token: String?, name: String?): ValidatedNel<Error, MyObject> =
        Validated.fromNullable(token, { MissingField("token")  }).toValidatedNel().zip(
                Validated.fromNullable(name, { MissingField("name")  }).toValidatedNel()) { token, name ->
          MyObject(token, name)
        }
    it kind of feels like i "shouldn't" need to call
    toValidatedNel
    for each
    Validated
    r
    • 2
    • 8
  • n

    Nathan Bedell

    10/15/2021, 6:56 PM
    I'm curious, has anyone ever tried anything like this in a non-trivial Kotlin application? I think that once multiple receivers come out, this technique will sort of be moot -- but for now it seems to me like a nice way of emulating them with just a single receiver parameter. This reminds me a lot of "mtl-style" programming in Haskell. https://gist.github.com/Sintrastes/dc09b2db881962767a160a3a9d484487
    r
    • 2
    • 3
  • j

    julian

    10/17/2021, 6:35 AM
    😲 1.0.0 doesn't have
    Coproduct
    ? How come? And what's the recommended alternative?
    r
    • 2
    • 3
  • o

    Oliver Eisenbarth

    10/17/2021, 8:53 AM
    Hi, someone on Twitter asked me, if Refined Types (Arrow Meta) would work with model classes, that are JPA entities. I said "I don't think so", but I'm very insecure when giving advice. I understand the private constructor / creation via companion object as mandatory and I don't see a way to teach H8 using that. Was that right? Thx in advance
    r
    • 2
    • 2
Powered by Linen
Title
o

Oliver Eisenbarth

10/17/2021, 8:53 AM
Hi, someone on Twitter asked me, if Refined Types (Arrow Meta) would work with model classes, that are JPA entities. I said "I don't think so", but I'm very insecure when giving advice. I understand the private constructor / creation via companion object as mandatory and I don't see a way to teach H8 using that. Was that right? Thx in advance
r

raulraja

10/18/2021, 8:53 AM
Hi @Oliver Eisenbarth The current version of refined types would be able to do that because the refinement and compile time evaluations happens over Companion invoke calls that are detached from the class instances themselves but we are removing that plugin in favor of Arrow-Analysis. Arrow-Analysis is currently in active development by @Alejandro Serrano Mena and myself and we have an ETA for first release by Dec 2021. This plugin can perform more complex data flow analysis and ensure code is safer even when you don’t use your own refined types. For a glimpse at what it can do you can check out the tests in this file https://github.com/arrow-kt/arrow-meta/blob/main/plugins/analysis/kotlin-plugin/src/test/kotlin/arrow/meta/plugins/analysis/AnalysisTests.kt Arrow-Analysis uses an smt solver and lifts the kotlin expressions ensuring pre, post and invariants are obeyed across the program dataflow. It report call sites and places that would otherwise not pass the requirements and provides information as to why. I originally developed the Refined types support as a prototype of what could be done with the Ir constant expression evaluator in the compiler. Finally when @Alejandro Serrano Mena joined me in this problem he convinced me there was a better way to do all this so we are abandoning the old refinements in favor of this plugin. In the test file you can find examples like
PostiveInt
, collection access and others that show outcomes of compilation with and without the plugin applied
o

Oliver Eisenbarth

10/19/2021, 9:33 AM
Hi @raulraja, thank you very much! I guess thinking of H8, I missed that refinement happens at compile time, before H8 can do it's reflection thing with the (synthetic, if
no-arg
plugin is used) public constructor. doh Please excuse me for giving advice without trying out things first. I'm still on parental leave and kinda lazy. I will tell the guy. 🙂 The new plugin sounds exciting. I will check out the tests! Thanks for making Arrow so accessible, you guys rock. 🤘
❤️ 1
View count: 13