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

    kobby

    06/18/2020, 11:42 AM
    I am trying to do something very basic like
    Either.Right("SOMETHING").map{it.toLowerCase()}
    and I'm getting
    Cannot access 'arrow.Kind' which is a supertype of 'arrow.core.Either'
    I already have arrow-core 0.10.5 and arrow-core-data 0.10.5 is there another library I need to bring in?
    p
    • 2
    • 2
  • v

    VladKopanev

    06/18/2020, 1:13 PM
    Hi Guys! I am wondering is there any generic function in arrow that helps turn a bunch of nullable values into a one nullable value given a function e.g. data class constructor, it could be smth like this:
    fun <A, B, C, D> fromNullable(a: A?, b: B?, c: C?, f: (A, B, C) -> D): D?
    s
    s
    • 3
    • 15
  • p

    pakoito

    06/18/2020, 7:21 PM
    android-ui or android-arch is something we’ve toyed with in the past. @Miguel Coleto knows about comonadic UIs, and I believe @aballano was interested at some point. What we’re missing is someone to take the initiative and drive the project to completion 😄 So if you’d like to take it and learn while you write, that’s how several other projects like Optics happened.
    💯 4
    🤘 3
    :arrow: 3
    s
    • 2
    • 2
  • j

    jem

    06/20/2020, 5:15 AM
    In my project I've defined the following extensions to avoid having to declare the id monad on Reader map and flatmap.
    /**
     * Extension function that fixes `Reader` so that you can `map` without needing to pass
     * `arrow.core.Id.monad()` explicitly.
     */
    fun <D, A, B> Reader<D, A>.map(f: (A) -> B): Reader<D, B> {
      return this.map(arrow.core.Id.monad()) { f(it) }
    }
    
    /**
     * Extension function that fixes `Reader` so that you can `flatMap` without needing to pass
     * `arrow.core.Id.monad()` explicitly.
     */
    fun <D, A, B> Reader<D, A>.flatMap(f: (A) -> KleisliOf<D, ForId, B>): Reader<D, B> {
      return this.flatMap(arrow.core.Id.monad()) { f(it) }
    }
    Is there any blocker for actually just making Reader work this way in the lib? Is there any other monad instance that is valid for Reader?
    s
    • 2
    • 4
  • m

    marc0der

    06/20/2020, 10:58 AM
    Hi arrow folks, I'm currently working on the FP in Kotlin chapter that deals with Monads 🎉 I've gotten to a point where I can't really express what I want to in Kotlin, and was hoping that Arrow could help me out here!
    r
    s
    • 3
    • 22
  • s

    stojan

    06/20/2020, 2:41 PM
    Arrow Fx + MTL
    override fun open(
            no: String,
            name: String,
            rate: Option<BigDecimal>,
            openingDate: Option<LocalDate>,
            accountType: AccountType
        ): AccountOperation<Account> = Kleisli.invoke { repo ->
            EitherT(
                repo.query(no).flatMap { accountOptionOrError ->
                    accountOptionOrError.fold(
                        { IO { MiscellaneousDomainExceptions(it).left() } },
                        { accOpt ->
                            accOpt.fold(
                                {
                                    when (accountType) {
                                        AccountType.CHECKING -> createOrUpdate(
                                            repo,
                                            Account.checkingAccount(no, name, openingDate, None, Balance())
                                        )
                                        AccountType.SAVINGS -> rate.map { r ->
                                            createOrUpdate(
                                                repo,
                                                Account.savingsAccount(no, name, r, openingDate, None, Balance())
                                            )
                                        }.getOrElse { IO { RateMissingForSavingsAccount.left() } }
                                    }
                                },
                                { IO { AlreadyExistingAccount(<http://it.no|it.no>).left() } }
                            )
                        }
                    )
                }
            )
        }
    the future:
    override suspend fun AccountRepository.open(
            no: String,
            name: String,
            rate: BigDecimal?,
            openingDate: LocalDate?,
            accountType: AccountType
        ): Either<AccountServiceException, Account> = either {
            val existing = query(no).mapLeft { MiscellaneousDomainExceptions(it) }.bind()
            existing.rightIfNull { AlreadyExistingAccount(no) }.bind()
    
            val accountOrError = when (accountType) {
                AccountType.CHECKING -> Account.checkingAccount(no, name, openingDate, null, Balance())
                AccountType.SAVINGS -> {
                    val r = rate.rightIfNotNull { RateMissingForSavingsAccount }.bind()
                    Account.savingsAccount(no, name, r, openingDate, null, Balance())
                }
            }
            createOrUpdate(this@open, accountOrError).bind()
        }
    the future is bright 😄
    😍 5
    r
    • 2
    • 21
  • j

    julian

    06/21/2020, 2:13 AM
    What is the relationship between use of typeclasses (or the Kotlin equivalent of interfaces with extension functions) and functional programming? Neither are required for core FP goals such as immutability, purity, and referential transparency. So, why does this pattern repeatedly show up in FP?
    s
    s
    m
    • 4
    • 12
  • g

    Gopal S Akshintala

    06/21/2020, 2:51 AM
    Is there a
    filterOrElse
    equivalent for BIO? Currently I had to write like this to set BIO to left of right state based on a boolean result (which feels boilerplate)
    val example: (IO<String, Int>) -> IO<String, Any?> =
                    { valueIO ->
                        valueIO.map(::someBooleanResult)
                                .flatMap { if (it) IO.just(it) else IO.raiseError("error") }
                    }
    s
    • 2
    • 7
  • p

    pakoito

    06/21/2020, 2:51 PM
    you may be missing an import
    f
    r
    • 3
    • 17
  • f

    Fudge

    06/21/2020, 5:16 PM
    Given such a data structure
    data class X(val name : String)
    data class Y(val x1: X, x2: X, x3 :X, x4: X)
    Is there an easy way to change the
    name
    value of all ocurrences of
    X
    instances in
    Y
    ? Using optics perhaps? Something like this:
    val y = Y(...)
    val newY = changeAllNames(y) {it + "foo"}
    r
    • 2
    • 1
  • r

    rt

    06/21/2020, 8:27 PM
    Hi. How do I get
    //metadebug
    -annotated classes to be displayed on compilation? is there some compiler switch or something? I cloned the arrow-meta-examples project but nothing gets printed into compiler output even though
    //metadebug
    is clearly there
    r
    • 2
    • 3
  • s

    simon.vergauwen

    06/22/2020, 9:20 AM

    https://www.youtube.com/watch?v=6sw8GAhUJz0▾

    😘 1
    :arrow: 11
    👌🏼 12
    s
    r
    +2
    • 5
    • 15
  • j

    julian

    06/22/2020, 7:09 PM
    I'm using the typeclassless style of DI via interface composition.
    class G
    class H
    
    interface A<T> {
        fun T.foo(t: T): T
    }
    
    interface B : A<G>
    
    interface C : A<H>
    
    interface E : B, C // Compiler error: Type parameter T of 'A' has inconsistent values: InterfaceComposition.G, InterfaceComposition.H
    Is there a way to get around the compiler error? My use case is that A is a generic handler of events of type T. So B and C are specific handler implementations for the events G and H. I would like to be able to do:
    val a: A = TODO()
    when (a) {
       is B, is C -> a.foo(..)
       else -> TODO()
    }
    Without a common base interface, I'd have to do:
    val a: A = TODO()
    when (a) {
       is B -> a.foo(..)
       is C -> a.foo(..)
       else -> TODO()
    }
    Thanks!
    k
    k
    • 3
    • 5
  • r

    Rizary

    06/22/2020, 10:00 PM
    Does anyone know about article or else that compare the android app size made using arrow library and other library?
    k
    s
    • 3
    • 3
  • j

    julian

    06/23/2020, 5:23 PM
    Does Arrow have something equivalent to Parallel in Cats, that abstracts over Monads but also supports parallel composition?
    s
    p
    • 3
    • 6
  • r

    raulraja

    06/24/2020, 10:59 AM
    https://twitter.com/raulraja/status/1275744359019929600
    :arrow: 12
    🙌🏾 1
    👏🏾 1
    s
    • 2
    • 2
  • b

    bjonnh

    06/24/2020, 6:59 PM
    If I do a partraverse, what would be the correct way to limit the number of elements that gets executed in parallel?
    r
    s
    r
    • 4
    • 17
  • b

    bjonnh

    06/24/2020, 7:56 PM
    oh ok now we need two types for IO
    s
    j
    • 3
    • 2
  • b

    bjonnh

    06/24/2020, 8:24 PM
    hmm I'm using that library in another software that is not using arrow, so I was using unsafeRunSync() , but it doesn't seem to exist anymore either
    r
    s
    • 3
    • 8
  • f

    Felix

    06/25/2020, 3:55 PM
    I'm rather curious on how coroutines are used to implement monad comprehensions on Kotlin. I believe I got the overall idea, however I'm failing to see the rationale for this "save and restore": • https://github.com/arrow-kt/arrow-core/blob/master/arrow-core-data/src/main/kotlin/arrow/typeclasses/MonadContinuations.kt#L35 • https://github.com/arrow-kt/arrow-core/blob/master/arrow-core-data/src/main/kotlin/arrow/typeclasses/MonadContinuations.kt#L37 Does anyone has any pointers to help clarify this? Namely, that save-restore always required? Thanks!
    a
    r
    • 3
    • 4
  • j

    julian

    06/25/2020, 11:17 PM
    How is the term
    syntax
    used in naming classes or packages in Arrow or apps that use Arrow? I've seen this pattern before, but I don't recall where. Is it used interchangeably with the term
    ops
    ? Or maybe it was in Scala code...
    s
    • 2
    • 5
  • j

    julian

    06/26/2020, 10:22 PM
    How is the recommended typeclassless DI technique different from the not-recommended Cake pattern from Scala? Swap out extension functions for regular ones, and are they basically the same?
    r
    • 2
    • 10
  • j

    julian

    06/28/2020, 5:33 PM
    Having made the switch to extensive use of extension functions, I'm struggling with how to organize them. OO was simpler in this way, because you simply added methods to the objects on whose data the methods operated, mostly. What general strategies do others apply in the context of FP? What's the impact of these strategies on unit testing the extension functions? For example, when extension functions on different receivers are all top-level and so share the same scope, isn't it more tricky to tease them apart in order to unit test each function in isolation from the others it may depend on in that scope? Or, in this scenario, does the "unit" in unit testing become the function under test AND all the other functions that it calls? If so, doesn't that become unwieldy as functions stack up on top of each other?
    r
    • 2
    • 21
  • s

    Sasha Chepurnoi

    06/29/2020, 2:24 PM
    Hello 👋 I am trying to use fibers to concurrently load data chunks but I do not fully understand how it works with IO when I fork/join/bind Fiber. My IO continue to run on another thread (from worker pool) but initially started on ‘http-io’. I want to fire some IO heavy operations earlier, then fire a few more and start awaiting. I have an IO.fx block where I create different IO and then fork them. I want to run them concurrently on dispatchers().io() and so far they are running ok. But I notice by console-log-debugging that after first joining fiber IO is running on another thread. Are there any options or probably another class for this use case?
    s
    • 2
    • 12
  • m

    matthew graf

    06/29/2020, 8:31 PM
    Has anyone had any problems pulling the 0.11.0-SNAPSHOT libraries lately? We’re using gradle to build, and I don’t think we’ve made any changes around dependencies or build process recently. Been seeing errors like this, when pulling arrow-kt libraries:
    [2020-06-29T19:32:38.437Z] * What went wrong:
    [2020-06-29T19:32:38.437Z] Execution failed for task ':core:kaptGenerateStubsKotlin'.
    [2020-06-29T19:32:38.437Z] > Could not resolve all files for configuration ':core:compileClasspath'.
    [2020-06-29T19:32:38.437Z]    > Could not resolve io.arrow-kt:arrow-mtl:0.11.0-SNAPSHOT.
    [2020-06-29T19:32:38.437Z]      Required by:
    [2020-06-29T19:32:38.437Z]          project :core
    [2020-06-29T19:32:38.437Z]       > Could not resolve io.arrow-kt:arrow-mtl:0.11.0-SNAPSHOT.
    [2020-06-29T19:32:38.437Z]          > Unable to load Maven meta-data from <https://oss.jfrog.org/artifactory/oss-snapshot-local/io/arrow-kt/arrow-mtl/0.11.0-SNAPSHOT/maven-metadata.xml>.
    [2020-06-29T19:32:38.437Z]             > Could not get resource '<https://oss.jfrog.org/artifactory/oss-snapshot-local/io/arrow-kt/arrow-mtl/0.11.0-SNAPSHOT/maven-metadata.xml>'.
    [2020-06-29T19:32:38.437Z]                > Could not GET '<https://www.jfrog.com/error?from=oss.jfrog.org&by=nginx-shared4c.gcoss-use1.jfrog.local>'. Received status code 403 from server: Forbidden
    Oddly enough, if I visit one of those oss.jfrog.org urls directly, I’m able to download that metadata file
    • 1
    • 1
  • t

    tim

    07/01/2020, 8:56 AM
    Good day all, I'm looking for feedback on two bits now that I'm a few weeks into my FP journey (which I love more every day 🙏 😍 :arrow:). Firstly I'm finding myself turning everything into a comprehension ... is that optimal or is it over zealous? Secondly, I've been toying with extension functions when I encounter different/nested combinations like Either<Either...>. In my current use case I have
    Either<A, List<Either<A, B>>
    so I've created two extension functions to unpack it:
    fun <L, R> List<Either<L, R>>.splitLeftAndRight(): Tuple2<List<L>, List<R>> {
        val left = mutableListOf<L>()
        val right = mutableListOf<R>()
    
        forEach {
            when (it) {
                is Either.Left -> left += it.a
                is Either.Right -> right += it.b
            }
        }
    
        return Tuple2(left.toList(), right.toList())
    }
    
    fun <A, B, C> Either<A, List<Either<A, B>>>.flattenAndMap(f: (Tuple2<List<A>, List<B>>) -> C): Either<A, C> =
        when (this) {
            is Either.Left -> a.left()
            is Either.Right -> {
                f(b.splitLeftAndRight()).right()
            }
        }
    And now in my comprehension becomes:
    .map {
      // something that returns Either<A, List<Either<A, B>>>
    }
    .flattenAndMap { (lefts, rights) ->
      log.warn { "Filtering nested lefts: $lefts" }
      rights
    }
    So my question here is, does this approach make sense, or is there something wrong with it/I've missed something in the FP toolbox that would make my life easier? Thank you!
    s
    j
    • 3
    • 15
  • t

    than_

    07/02/2020, 12:39 PM
    hi, is there something like mapN for Validated? Something like:
    fun <V1, V2, ..., V22, E, R)validatedMapN(v1: Validated<E,V1>, v2: Validated<E,V2>, ..., v22: V22, sg: Semigroup<E>, f: (V1, V2, ..., V22)->R): Validated<E, R>
    f
    • 2
    • 2
  • a

    addamsson

    07/05/2020, 12:04 PM
    Is Arrow multiplatform yet?
    👀 1
    s
    • 2
    • 5
  • m

    marc0der

    07/07/2020, 3:36 PM
    Hi folks, I was just looking at the
    curry()
    extension methods on functions of arity 2 in arrow-core: https://github.com/arrow-kt/arrow-core/blob/master/arrow-core-data/src/main/kotlin/arrow/core/predef.kt#L5
    f
    • 2
    • 3
  • t

    Tristan MARIE

    07/08/2020, 2:00 PM
    what i'm doing is just reading the arguments given from ktor (which are nullable string), use them to retrieve a planning and add to it the PlanningDay given by the user in the request
    r
    s
    f
    • 4
    • 3
Powered by Linen
Title
t

Tristan MARIE

07/08/2020, 2:00 PM
what i'm doing is just reading the arguments given from ktor (which are nullable string), use them to retrieve a planning and add to it the PlanningDay given by the user in the request
r

raulraja

07/08/2020, 2:32 PM
Hi Meimei, no point in using Option there if you already have a way to extract args as nullable types
☝️ 1
s

simon.vergauwen

07/08/2020, 3:16 PM
There are also constructors to go straight from
A?
to
Either<E, A>
. Where you have to supply a fallback
E
value. You can find it as
rightIfNull
there are runnable examples on the website. https://arrow-kt.io/docs/0.10/apidocs/arrow-core-data/arrow.core/-either/#syntax
f

fteychene

07/08/2020, 3:19 PM
Hi 👋 Agree with not using option For the rest of the code I would translate to something like that if the errors types aligns (that seems to be the case from your snippet)
post("...") {
    val dayToAdd: Either<ServerError, String> = ...
    val year: Either<ServerError, Int> = ...
    val month: Either<ServerError, String> = ...

    dayToAdd.product(year).product(month)
        .flatMap{ (dayToAdd, year, month) ->
            PlanningService.getOrCreate(year, month)
                .map { planning -> PlanningService.addDayToPlanning(planning, dayToAdd) }
        }
        .fold(
            { /* Respond Error */ println(it) },
            { /* Respond */ println("Success") }
        )
}
If i'm wrong please let me know 😅
☝️ 1
View count: 3