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

    kierans777

    02/14/2022, 2:31 AM
    I'm writing a library that I want to be cross compiled to iOS. I have a function type which returns an
    Either
    eg:
    (Any) -> Either<A, B>
    and I want Swift authors to be able to write functions that conform to that signature to be passed into functions in my library. That way I can delegate certain platform specific ideas to the platform. However I can't seem to be able to create an
    Either
    in Swift code. Looking in the MPP generated headers, I can see the
    Arrow_coreEither
    type with its methods (eg:
    bimap
    ) but I can't find the
    Right
    or
    Left
    constructors. Is there something I have to do in my Kotlin project to expose the types properly? Has anyone done this successfully?
    s
    1 reply · 2 participants
  • b

    Bart Kleijngeld

    02/15/2022, 12:00 PM
    This is a bit pedantic maybe, but I was hoping people could share their opinion on how they name function parameters and types in a way where you don't unnecessarily repeat (or leave out) information.
    r
    t
    15 replies · 3 participants
  • g

    Gopal S Akshintala

    02/15/2022, 12:49 PM
    NonEmptyList<A>
    is an awesome data-structure, I reckon one of it’s use-cases can be as a param to force callers to pass non-empty lists. But any reason why there is no
    NonEmptySet<A>
    ?
    s
    1 reply · 2 participants
  • s

    Srki Rakic

    02/15/2022, 5:02 PM
    I'm looking through this example and wonder if Exception handling is intentionally omitted here (all the way down the stack)? My assumption is that the function is defined as
    suspend
    because it is making a network call (not pure), but I'm curious what would be the recommended approach to handling exceptions.
    r
    s
    7 replies · 3 participants
  • n

    noone

    02/16/2022, 1:31 PM
    Does a book exist or video tutorials?
    🤨 1
    j
    1 reply · 2 participants
  • s

    SecretX

    02/18/2022, 11:14 PM
    how can I return a raw value as the left value when inside an either block? E.g.
    fun test() = either<String, SomeObject> {
        val someString = ""
        // how can I return 'someString' as the left value of this either?
    }
    w
    a
    2 replies · 3 participants
  • g

    Gavin Ray

    02/19/2022, 5:06 PM
    given/using
    was one of the biggest things I really missed compared to coding in Scala and now Kotlin essentially has it 😅
    r
    1 reply · 2 participants
  • s

    Sourabh Rawat

    02/22/2022, 6:35 AM
    Hi, I am not able to see proper stacktrace and line numbers when a runtime exception is thrown in an
    effect
    block. I get something like
    at foo.bar.BookService$bookReservation$suspendImpl$$inlined$invoke$1.invokeSuspend(Effect.kt:44) ~[main/:?]
    at foo.bar.BookService$bookReservation$suspendImpl$$inlined$invoke$1.invoke(Effect.kt) ~[main/:?]
    at foo.bar.BookService$bookReservation$suspendImpl$$inlined$invoke$1.invoke(Effect.kt) ~[main/:?]
    at arrow.continuations.generic.SuspendMonadContinuation.startCoroutineUninterceptedOrReturn(SuspendingComputation.kt:89) ~[arrow-continuations-jvm-1.0.1.jar:?]
    at arrow.continuations.Reset.suspended(Reset.kt:27) ~[arrow-continuations-jvm-1.0.1.jar:?]
    at foo.bar.BookService.bookReservation$suspendImpl(BookService.kt:104) ~[main/:?]
    Line number 104 does not even exist... Edit: Same as https://github.com/arrow-kt/arrow/issues/2647
    s
    r
    3 replies · 3 participants
  • g

    gabib

    02/23/2022, 10:54 AM
    hi, a friend of mine wrote the first article in a series about domain validation in Kotlin with Arrow [https://medium.com/@tibtof/domain-model-validation-in-kotlin-part-1-21fa44c60ef3]
    👀 1
    ❤️ 6
    r
    t
    +1
    12 replies · 4 participants
  • j

    jean

    02/24/2022, 8:31 AM
    Is there a better approach to this code?
    // create a hash from clear password
    return hashPassword(password, pbkdf2Values)
         // search for email/hash pair in db
        .flatMap { database.findUserByCredentials(email, it) }
        .map {
            // if user is registered, check for existing auth token 
            when (val existingToken = database.token(it, userAgent)) {   
                is Either.Left -> createToken(jwtValues, it, userAgent) // no token -> create a new one
                is Either.Right -> existingToken.value // token exists -> return it
            }
        }
    I tried to use
    either.eager{}
    or
    fold(ifLeft, ifRight)
    but I didn’t find any solution more convincing 😕
    s
    s
    5 replies · 3 participants
  • n

    Norbi

    02/24/2022, 10:26 AM
    Is it possible to modify an object by applying multiple `Lens`es in one turn? It causes lots of new object creation if I apply them sequentially...
    s
    c
    4 replies · 3 participants
  • c

    carbaj0

    02/25/2022, 10:28 AM
    Hi! Lately, I’ve been wondering how helpful Currying, Compose and Pipe are in the Kotlin FP world. is something that i should be using regularly as kotlin fp programmer? or is something more useful for programming languages like Haskell?
    r
    s
    +4
    12 replies · 7 participants
  • c

    carbaj0

    02/27/2022, 6:37 PM
    👋, i bring you another doubt, always thinking from the FP point of view, purity above all hehe
    s
    j
    15 replies · 3 participants
  • c

    carbaj0

    03/01/2022, 12:13 PM
    When will we have the
    EffectScope<>
    refactor available? I’m looking forward to trying it 😋
    s
    2 replies · 2 participants
  • t

    Tower Guidev2

    03/01/2022, 1:45 PM
    Hi iam trying to switch to Arrow exception handing within my current android application it appears to working ok up to now i would appreciate some advice on the following code is this a valid use of "`either {}`" with a single "`bind()`" containded within it? is there any "better" alternative?
    val work: Either<DatasourceException, *> = either { persistOutcome().bind() }
    r
    s
    +1
    4 replies · 4 participants
  • c

    Cody Mikol

    03/01/2022, 5:32 PM
    is there something like
    parZip
    that just returns a
    TupleN
    ?
    s
    3 replies · 2 participants
  • t

    Ties

    03/02/2022, 2:36 PM
    I am looking into arrow analysis and it talks a bit about
    require
    being invariant, and pre/post conditions being something different.
    fun increment(x: Int): Int {
        pre(x > 0) { "value must be positive" }
        return x + 1
    }
    
    fun increment2(x: Int): Int {
        require(x > 0) { "value must be positive" }
        return x + 1
    }
    But here both seem to work the same, and if I look into the code I see pre() is just calling require. If I then look at the examples in the documentation (https://arrow-kt.io/docs/meta/analysis/types/)class
    Positive(val value: Int) {
      init { require(value > 0) }
    }
    
    and 
    
    class Positive(val value: Int) {
      init { 
        pre(value > 0) { "value must be positive" }
        post({ this.value > 0 }) { "value is positive" }
      }
    }
    could the second example also be written
    class Positive(val value: Int) {
      init { 
        require(value > 0) { "value must be positive" }
        post({ this.value > 0 }) { "value is positive" }
      }
    }
    and it being the same thing? or is there a difference between pre and require?
    r
    4 replies · 2 participants
  • s

    Stylianos Gakis

    03/04/2022, 11:05 AM
    Hey new to Arrow here, using only Core so far and I got a question, probably a bit stylistic about how code looks like. I often find myself at the end of a chain where I got an
    Either
    to want to do something with the result, whether it’s left or right. 1. I see there’s one alternative of assigning the result to a value and doing a
    when
    on it, which works but feels a bit “extra”. 2. I can do a
    tap
    and a
    tapLeft
    which i don’t like because I’m doing it in two functions. 3. There is also
    fold
    which is what I am using the most, but this also comes with folding the two types into one which isn’t what I am looking to do in those scenarios. I would like to be able to have an alternative that does basically what tap/tapLeft does but for both cases. And now I wonder, does this not exist right now because: 1. It’s too easy to simply do our own implementation of it 2. No good name exists to denote such a behavior 3. It’s generally not a good idea and if I am looking to do something like this I probably want to do something else instead And I feel like the 3rd option is what’s happening here so I wanted to bring this up here to see what people generally do in those cases 🤔
    s
    r
    +1
    15 replies · 4 participants
  • t

    Ties

    03/07/2022, 4:22 PM
    Hey, i'm experimenting with Arrow Analysis, and I noticed something. I think I kinda guess why this works like this, but thought it would be interesting to share: I was trying to see how far I can take Arrow Analysis and I was writing a Spring Boot application and tried to see what happened if I used this as a
    PathVariable
    @RestController
    class MyController {
    
        @JvmInline
        value class Positive(val value: Int) {
            init { require(value > 0) }
    
            operator fun plus(other : Positive) = Positive(this.value + other.value)
        }
    
        @GetMapping("/{id}")
        fun getTypeWithId(@PathVariable("id") id : Positive) : ResponseEntity<Positive>{
            println(id)
            return ResponseEntity.ok(id)
        }
    }
    Turns out, if I send a request with the value
    -1
    it will actually print and return
    -1
    , so I just managed to create a Positive negative value 😄 So it compiles, and it seems that jackson is ignoring the
    require
    when creating a value class. (I am aware that this is not Arrows fault, just wanted to share)
    e
    s
    +1
    6 replies · 4 participants
  • s

    simon.vergauwen

    03/08/2022, 2:29 PM
    Does anyone have experience with
    ReplaceWith
    ? https://kotlinlang.slack.com/archives/C0B8H786P/p1646749747028839
    c
    4 replies · 2 participants
  • k

    kierans777

    03/09/2022, 12:52 AM
    I feel like a bit of a n00b because I find the Monoid docs not really helpful in understanding how to use Monoids in Arrow (I use them regularly in other FP programs). I have a
    List<Map<String, String>>
    and I want to fold it down to
    Map<String, String>
    . How could I do this using a Monoid in Arrow?
    s
    6 replies · 2 participants
  • t

    than_

    03/09/2022, 10:05 AM
    https://kotlinlang.slack.com/archives/C5UPMM0A0/p1646811136681089?thread_ts=1646787156.669429&amp;cid=C5UPMM0A0
    Iterable::combineAll
    looks to be the same as
    Iterable::fold
    or am I missing something?
    s
    5 replies · 2 participants
  • s

    Shalom Halbert

    03/10/2022, 9:04 PM
    Currently using something like
    fun onSomethingChecked(isTrue: Boolean, onTrue: () -> Unit, onFalse: () -> Unit) {...}
    s
    m
    6 replies · 3 participants
  • s

    Shalom Halbert

    03/10/2022, 9:29 PM
    Option<Unit>
    seems like a better option than
    Either
    t
    2 replies · 2 participants
  • m

    Marius Kotsbak

    03/15/2022, 2:00 PM
    I'm testing https://arrow-kt.io/docs/meta/analysis/ but it has some blocking errors for our projects: https://github.com/arrow-kt/arrow-meta/issues/1031 https://github.com/arrow-kt/arrow-meta/issues/1032
    a
    1 reply · 2 participants
  • f

    Florian Magin

    03/16/2022, 12:51 PM
    hey, quick question: I have just been pointed towards the (haskell) concepts of "SYB/uniplate/Control.Lens.Plated" to use instead of the typical visitor pattern for rewriting abstract syntax trees. Does Arrow have anything in that direction already? Arrow has something called
    Lens
    as part of the
    Optics
    component, but I don't know if this is the same idea, and because I am not familiar with those concepts already, I'd rather focus on learning and understanding the thing I actually need for my project, not something else that happens to have the same name 😅
    s
    26 replies · 2 participants
  • j

    julian

    03/17/2022, 7:11 PM
    I'm playing with Arrow Analysis (AA). It seems like
    require
    is treated differently by the compiler compared with a project that doesn't use AA. Is this a correct observation? For example, this, which doesn't explicitly use any AA features,
    fun fn() {
        val x = 1
        require(x == 1)
    }
    results in a compiler error:
    could not parse predicate: x == 1
    Whereas in a project without AA, there's no compiler error.
    a
    r
    5 replies · 3 participants
  • c

    Cody Mikol

    03/17/2022, 9:12 PM
    where you can have something like
    Option<String?>
    w
    5 replies · 2 participants
  • p

    phldavies

    03/18/2022, 12:24 PM
    Is there a nice way to map an either through a lambda that might throw and catch/map the exception to left? At the moment I have
    fetch(key).flatMap { Either.catch({ Malformed(key) }) { f(it) } }
    s
    1 reply · 2 participants
  • y

    Youssef Shoaib [MOD]

    03/19/2022, 6:15 PM
    Inspired by Given from arrow, I made this small little utility function that has been really useful with context receivers. The advantage it has is that the `this@`convention doesn't work if you have multiple receivers that are of the same type but with generics (i.e 2 lists):
    context(A) fun <A> given(): A = this@A
    sadly the type needs to be specified whenever
    given
    is used because it doesn't infer the type parameter from usage (it instead latches onto the closest receiver).
    ❤️ 2
    g
    r
    8 replies · 3 participants
Powered by Linen
Title
y

Youssef Shoaib [MOD]

03/19/2022, 6:15 PM
Inspired by Given from arrow, I made this small little utility function that has been really useful with context receivers. The advantage it has is that the `this@`convention doesn't work if you have multiple receivers that are of the same type but with generics (i.e 2 lists):
context(A) fun <A> given(): A = this@A
sadly the type needs to be specified whenever
given
is used because it doesn't infer the type parameter from usage (it instead latches onto the closest receiver).
❤️ 2
g

Gavin Ray

03/19/2022, 6:33 PM
Sorry if this is a dumb question -- but what does this do exactly?
y

Youssef Shoaib [MOD]

03/19/2022, 6:39 PM
oh It's just for when you have context receivers (with the new prototype) so that you can pick one out based on a type. For instance:
context(List<Int>, List<String>, Long)
fun doSomething() {
    repeat(given<Long>() {
        println(given<List<Int>>().last())
        println(given<List<String>>().first())
    }
}
Because the recommended way is to use the
this@List
notation, which doesn't accomodate generics. This is inspired by
given
which used to be a feature in Arrow Meta that did almost the same thing
r

raulraja

03/19/2022, 6:52 PM
thanks for sharing @Youssef Shoaib [MOD], related, @Imran/Malic is moving the proofs plugin to its own repo and @Javier and I are working in providing:
@Context annotation class Config
@Context annotation class Persistence


@Config fun a(): A = ...
@Persistence fun b(): B = ...

context(A, B)
fun foo() {}

materialize<@Config A, @Persistence B>.foo()
That is DI for context receivers in addition to namespaced isolated injection based on type resolution. No source codegen just compiler substitutions in FIR and IR. If FIR works as expected IDEa will tell you when you are missing provider and other resolution errors when materializing.
👀 1
😍 1
g

Gavin Ray

03/19/2022, 7:10 PM
Because the recommended way is to use the
this@List
notation, which doesn't accomodate generics.
Ohhh, got it that makes perfect sense. I've used Scala 3's `given`/`using` so I'm a bit familiar with the context receivers concept but I didn't know it had this limitation -- thanks for sharing!
That is DI for context receivers in addition to namespaced isolated injection based on type resolution. No source codegen just compiler substitutions in FIR and IR.
That looks fantastic! One of the biggest uses I've had for
given
in Scala 3 was easy DI, since you can just declare singleton objects and then inject them with
(using config: Config)
How do the annotations work here exactly?
r

raulraja

03/19/2022, 9:45 PM
In scala implicit injection is scoped and you have to tag your types if you want name based or similar resolution. In our case in Kotlin injection will be coherent like in haskell (no local scopes or complex discovery of instances, only top level) . We provide an annotation`@Context` that users can use to create their own annotations. Each context resolves its types independently than other context. This allows you to have multiple provider of the same type without ambiguity for different contexts.
🙌 1
Orphan instances and local overrides of instances is allowed if you make your providers
internal
making them of higher priority in candidate resolution
View count: 2