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
functional
  • s

    Sourabh Rawat

    12/16/2021, 7:09 PM
    Hi, I have an
    either
    block from which I want to return a
    Left
    value without any
    bind
    calls. For example
    either<Error, Response> {
     when(foo) {
      1 -> callFunReturningEither().bind()
      else -> Error("foo is in else") <-- How to return this Left value?
     }
    }
    I have tried
    Error("foo is in else").left().bind()
    but it gives
    Returning type parameter has been inferred to Nothing implicitly. Please specify type arguments explicitly to hide this warning. Nothing can produce an exception at runtime.
    which I think is expected.
    r
    s
    p
    • 4
    • 5
  • p

    pakoito

    12/24/2021, 2:33 AM
    wat
    r
    • 2
    • 1
  • w

    wakingrufus

    01/25/2022, 10:24 PM
    what was the reason that the arity of function types maxed out at 22 originally? (before FunctionN). is there something special about 22 or was it arbitrary?
    e
    e
    • 3
    • 4
  • j

    Jerry Liu

    03/25/2022, 3:37 PM
    Hey folks, this is Jerry from DoorDash! When DoorDash moved from a monolith to microservices my team was looking for ways of making our code cleaner and more reliable. One of the low-hanging fruits was to utilize functional programming more instead of pure imperative programming/OOP when using Kotlin for writing backend services. I thought I would share some of these experiences with the developer community and wrote this guide “How to leverage functional programming in Kotlin to write better, cleaner code” that explains: The differences between FP and imperative programming and how to code different use-cases in Koltin with FP vs Imperative.
    🎉 6
    👌 1
    👌🏼 1
    p
    • 2
    • 2
  • d

    dp

    04/14/2022, 9:12 PM
    I’m just getting started with learning Kotlin and at the same time I’m trying to advance my functional programming understanding/skills. My background is in web development with JS (using functional/declarative libraries like Ramda and XState). Is there a recommend learning path? Books, tutorials, videos, etc. Thanks!
    p
    • 2
    • 17
  • m

    Muhammad Talha

    04/28/2022, 7:22 AM
    Hope this is the right place to ask this, since this is like an Either type. I’m using the following sealed class to return success or error types (credit to https://phauer.com/2019/sealed-classes-exceptions-kotlin/). It’s working great. I can use the
    Outcome.Success
    class with a value. However is it possible to use it without a value? There are some cases where I don’t want to pass a value in. I’m not quite sure what the definition would be for me not to pass a value in while not making value optional. Thanks!
    sealed class Outcome<out T: Any> {
        class Success<out T: Any>(val value: T) : Outcome<T>()
        class Error(val msg: String, val exp: Exception? = null) : Outcome<Nothing>()
    }
    s
    • 2
    • 4
  • u

    Uberto Barbini

    06/30/2022, 6:55 AM
    I wrote a series of three posts about how to use Functional Programming principles to design a web application in Kotlin: https://medium.com/pragmatic-programmers/from-objects-to-functions-c317f857bcea
    👍 2
    👍🏼 2
    :kotlin-intensifies-purple: 7
    j
    • 2
    • 1
  • i

    imashnake_

    07/09/2022, 8:22 AM
    Does anyone know if lambdas can have extension functions? By the looks of it I assume not but I'm not sure why they shouldn't.
    r
    w
    • 3
    • 3
  • r

    reactormonk

    07/14/2022, 12:55 PM
    Is there a parser-combinator that works on top of
    Flow
    ?
    👀 3
  • r

    Rohde Fischer

    07/31/2022, 1:59 PM
    when working with an
    Either
    I sometimes run into having multiple results where I need the results for another call. There I'm usually end up in an ugly structure with nested `flatMap`s. E.g.:
    val result1 = foo() // : Either<Error, Result1>
    val result2 = foo() // : Either<Error, Result2>
    val result3 = foo() // : Either<Error, Result3>
    
    val transformed = result1.flatMap { res1 ->
        result2.flatMap { res2 ->
            result3.flatMap { res3 -> someCall(res1, res2, res3) }
        }
    }
    isn't there a nicer way to do this?
    y
    • 2
    • 3
  • m

    Muhammad Talha

    08/16/2022, 4:59 AM
    Hi all - I’m new to FP in Kotlin (and in general 😅) - Is it practical (from a performance and dev ergonomics standpoint) in Kotlin to use higher order functions and partial application to inject dependencies to aim for a functional approach? E.g. if I want to use a database connection in a getUsers function, is it performant to partially apply the database object then use the getUsers function that way? Or would this cause problems down the line and I should just stick to traditional dependency injection with a class constructor?
    d
    • 2
    • 6
  • r

    Ricky Clarkson [G]

    08/16/2022, 6:18 AM
    I don't think you would see performance issues, but you might see code becoming less readable. There is no partial application in the language, though you can certainly emulate it.
  • m

    Muhammad Talha

    08/16/2022, 6:29 AM
    I see so overall it would be recommended to avoid it and prefer classes for dependencies? Is idiomatic FP in kotlin more on the business logic side and not so much dealing with the dependencies and stateful code?
  • s

    simon.vergauwen

    08/16/2022, 7:13 AM
    Hey @Muhammad Talha, not sure if you've seen #arrow which explores and offers a lot of utilities to do FP in Kotlin. I would say in general partial application is not very Kotlin idiomatic, and traditional DI with class constructors and modules is more idiomatic. An example, https://github.com/nomisRev/ktor-arrow-example/blob/main/src/main/kotlin/io/github/nomisrev/env/Dependencies.kt
    m
    e
    • 3
    • 2
  • r

    reactormonk

    09/02/2022, 1:22 PM
    I've got
    kotlin
    @JsonClass(generateAdapter = true)
    data class Gallery<T>(val galleryItems: List<GalleryItem<T>>)
    
    @JsonClass(generateAdapter = true, generator = "sealed:type")
    sealed interface GalleryItem<T> {
        @TypeLabel("photo")
        @JsonClass(generateAdapter = true)
        data class Photo<T>(val url: T): GalleryItem<T>
        @TypeLabel("video")
        @JsonClass(generateAdapter = true)
        data class Video<T>(val url: T): GalleryItem<T>
    }
    And
    val x: Gallery<String>
    as well as
    fun parse(x: String): HttpUrl
    and I would like a
    Gallery<HttpUrl>
    in the end. In Haskell, I'd add a
    deriving Functor
    to the type declaration and then I could use all the fun combinatorics functions. How would I do that in Kotlin?
    s
    • 2
    • 21
  • n

    Nathan Bedell

    09/28/2022, 9:01 PM
    Hi all, figured here might be a good place to ask. I'm looking for a DI framework that satisfies the following constraints: 1. Doesn't use reflection (Don't want to deal with proguard nonsense more than nesecsary). 2. Compile-time validation of inject statements (I want to know before me code compiles if I try to inject something I haven't provided in a module). 3. Doesn't force you into using OO constructs (I want to be able to use injection in standalone functions and extension methods). Anything like this out there? Koin I think is the closest so far, satisfying 3 but not the others. Heck, I'd even take just 2 & 3 as long as the proguard config isn't too bad to set up and works well in practice without a lot of headaches. And of course context receivers probably solves all three, but they're not ready for production. Ditto for manual parameter passing, but my code-base is getting to the size where I am trying to ease the manual parameter passing burden a bit.
    m
    s
    • 3
    • 2
  • t

    Ties

    10/17/2022, 6:35 PM
    Wrote a blog about the problems with FP today: https://blog.jdriven.com/2022/10/the-problem-with-functional-programming/ (dont worry 😛 its not that negative)
    s
    u
    • 3
    • 3
  • r

    reactormonk

    10/21/2022, 12:53 PM
    Is there a way to match on two boolean variables at the same time with a single
    when
    statement? Aka
    when (Pair(x, y)) {
      Pair(true, false) -> ...
    }
    r
    y
    k
    • 4
    • 5
  • r

    reactormonk

    10/28/2022, 11:41 AM
    Is there a way to only match part of a
    Pair
    match?
    val mimes = rec.mimeType.split("/")
    when (mimes[0] to mimes[1]) {
      "text" to "vcard" -> {}
      "video" to _ -> {}
    }
    ^ the second one isn't really working out.
    j
    • 2
    • 2
  • k

    Kristian Nedrevold

    11/09/2022, 8:24 PM
    In Rust I can do this:
    struct Circle {
        radius: u32,
    }
    
    impl Circle {
        fn new(radius: u32) -> Circle {
            Circle { radius }
        }
    }
    
    trait Shape {
        fn area(&self) -> f64;
        fn perimeter(&self) -> f64;
    }
    
    impl Shape for Circle {
        fn area(&self) -> f64 {
            std::f64::consts::PI * (self.radius as f64).powi(2)
        }
    
        fn perimeter(&self) -> f64 {
            2.0 * std::f64::consts::PI * (self.radius as f64)
        }
    }
    
    fn pretty_print<T: Shape>(shape: T) {
        println!("Area: {}", shape.area());
        println!("Perimeter: {}", shape.perimeter());
    }
    
    fn main() {
        let circle = Circle::new(1);
    
        pretty_print(circle);
    }
    So the trait is like a Kotlin Interface. And now my function pretty_print can take any type(struct) that implements Shape. This seems like a very powerful feature to me as it means I can extend types. How can I achieve the same thing in Kotlin?
    e
    s
    • 3
    • 13
  • g

    gsala

    12/02/2022, 8:34 AM
    Is there a name for this patter in functional programming? What would you name the function?
    fun ((A, B) -> Unit).whatShouldThisBeNamed(b: B): (A) -> Unit {
            return { a -> this(a, b) }
        }
    (A function that returns a simpler function by providing one of the parameters to the first function)
    e
    a
    t
    • 4
    • 7
  • s

    Szymon Sasin

    12/05/2022, 7:02 PM
    Hi, lets say I have a sequence of objects (for simplicity I use strings):
    val s = sequenceOf("Lorem", "ipsum", "dolor", "sit", "amet")
    What’s the best way to limit elements so total size is smaller than desired. For example:
    val s2 = s.someFunction(maxSize = 17) { it.length }
    println(s2.toList()) // [Lorem, ipsum, dolor]
    c
    s
    e
    • 4
    • 9
  • m

    Marius Kotsbak

    12/08/2022, 12:09 PM
    @elizarov Testing using context receivers for type classes (as claimed in the KEEP should be possible?) Why isn't this working?:
    interface ServiceLocator<I> {
    //    fun getRealImpl(): I
        fun getEmulatedImpl(): I
    //    fun getStubbedImpl(): I
    }
    
    context(ServiceLocator<I>)
    inline fun <reified I> locateEmulated(): I = getEmulatedImpl()
    
    object StringServiceLocator : ServiceLocator<String> {
        override fun getEmulatedImpl(): String = "test"
    }
    
    object LongServiceLocator : ServiceLocator<Long> {
        override fun getEmulatedImpl(): Long = 5
    }
    
    object StringLongLocatorFactory: ServiceLocatorFactory {
        // In the future (scope properties): with val ...
        inline fun <reified I> locate(): I {
            with(LongServiceLocator) {
                with(StringServiceLocator) {
                    return locateEmulated<I>()
                }
            }
        }
    }
    No required context receiver found: Cxt { context(ServiceLocator<I>) public inline fun <reified I> locateEmulated(): I defined in [...] in file ServiceLocatorFactory.kt[SimpleFunctionDescriptorImpl@1aa4cbc9] }
    y
    u
    • 3
    • 16
  • k

    Kristian Nedrevold

    12/27/2022, 2:22 PM
    Working through category theory for programmers and doing the exercises in Kotlin. What is wrong with this memoize function?
    fun <A, B> memoize (f: (A) -> B) = { a: A ->
        val cache = mutableMapOf<A, B>()
        cache.computeIfAbsent(a) { f(a) }
    }
    m
    • 2
    • 9
  • r

    reactormonk

    12/29/2022, 2:00 PM
    I've got a problem statement where it would be really helpful to be able to match on about 4 variables (incoming states from different subsystems, and a requested state, and possibly even previous states), are there some compiler plugins / good workarounds for that?
    p
    • 2
    • 4
  • j

    julian

    01/05/2023, 6:14 PM
    I started a Discord server for folks working through the book FP Made Easier by C Scalfani. Here's an invite (good for 7 days).
  • b

    Breaker ACT

    02/01/2023, 3:00 AM
    Hi buddies. Do you have any sample code about apply FP/Arrow to CleanArchitect Android app ?
    b
    • 2
    • 2
  • p

    Piotr Krzemiński

    02/08/2023, 7:51 AM
    I’m thinking about creating a tool that would promote a more functional approach in certain contexts, like forbid using
    var
    or
    for
    loops (mutability in general), with a way to opt out in certain cases. Think: a step towards more pure FP. I’m wondering if you’d be keen to use it and, if yes, what approach you’d suggest to implement it. I’m thinking about a detekt rule or a compiler plugin that would emit an error or a warning (configurable)
    s
    • 2
    • 2
  • t

    Teimatini Marin

    02/10/2023, 4:39 PM
    Hi all! I'm reading a huge file/object from a remote source in bunches... send fragments of the file thru a Flow and wanna process complete lines one by one. I got below implementation... but I was wondering if there is a way to get rid of the var and get a more functional solution. Thanks in advance.
    fun main() = runBlocking {
        var lastline = ""
        readHugeFile().collect { value ->
            val lines = (lastline+value).lines()
            lines.dropLast(1).forEach {
                println(it)
            }
            lastline = lines.last()
        }
        println(lastline)
    }
    
    fun readHugeFile(): Flow<String> = flowOf(
        """line 1
            |line 2
            |li""".trimMargin(),
        """ne 3
            |line 4
            |lin""".trimMargin(),
        """e 5
            |line 6
            """.trimMargin()
    )
    a
    • 2
    • 2
  • d

    dave08

    02/13/2023, 4:50 PM
    Somebody was telling me that ArrowKt changes a lot... (maybe that was a conclusion he made having used it in previous, less stable versions?) does that mean there are often breaking changes? Is Arrow now stable in it's api? I know that there's always a will to improve as long as the language itself doesn't support all of the features a functional language would need...
    r
    s
    • 3
    • 10
Powered by Linen
Title
d

dave08

02/13/2023, 4:50 PM
Somebody was telling me that ArrowKt changes a lot... (maybe that was a conclusion he made having used it in previous, less stable versions?) does that mean there are often breaking changes? Is Arrow now stable in it's api? I know that there's always a will to improve as long as the language itself doesn't support all of the features a functional language would need...
r

raulraja

02/13/2023, 5:11 PM
Hi Dave, Arrow gained this reputation in the 0.x series as we removed most of the type classes and abstractions we used when the lib originated. Since the 1.x series it's stable and new features are frequently back-ported to older versions.
s

simon.vergauwen

02/13/2023, 5:42 PM
0.x series
To put some more perspective, Arrow 1.x was release almost 2021 and Arrow 2.x is being released later this year. Within 1.x.x there were no breaking changes, and the last version of 1.x.x will be source compatible with 2.x.x. 1.x.x -> 2.x.x will remove some obscure APIs, and further clean-up some old legacy things that are not being used.
d

dave08

02/13/2023, 6:27 PM
Thanks for the answers! So the new 2.x.x API will be stable and it's all already in 1.x.x? Is some of it expected to be deprecated if, say, new features in the language would be added?
s

simon.vergauwen

02/13/2023, 6:30 PM
We're deprecating everything in 1.x.x before effectively removing it in 2.x.x, and almost everything is back-ported. The next minor version will be the last 1.x.x release (1.2.x), and all non-deprecated methods will be source-compatible in 2.0.0. It'll be released soon-ish with a "migration guide" to fix all deprecated methods. 2.x.x (and 1.2.x) is build with new language features (context receivers) in mind, so if 3.x.x is released in the future it'll be with very minimal changes.
very minimal changes
This can be done in a binary compatible way, so we might just stick to 2.x.x even when context receivers land into the language.
If you're interested in using 1.2.x already, you can use
1.1.6-alpha.26
and check the PRs for all remaining work that is still to be merged before the
1.2.x.
release ☺️
The alpha release are stable, and are also binary compatible with everything in 1.x.x
d

dave08

02/20/2023, 2:58 PM
I'm starting to grasp the value of Arrow now, I might try it in a new service... you said the Alpha is stable, but is it production-ready? (I'd suppose not -- but you used it in your video...) Also, even if not, maybe it would be possible to have a release with a bunch of typealiases with the new names to avoid new projects having to migrate?
s

simon.vergauwen

02/20/2023, 3:29 PM
is stable, but is it production-ready?
Yes, it's production-ready.
Also, even if not, maybe it would be possible to have a release with a bunch of typealiases with the new names to avoid new projects having to migrate?
This is already the case, current
1.1.6-alpha.x
is what will be released as
1.2.x
in 2-3 weeks and all non-deprecated code will be source and binary-compatible with
2.x.x
.
1.2.x
is
1.1.x
+ everything from
2.x.x
back-ported.
@Deprecated
if it will be removed from
1.x.x
->
2.x.x
and all non-deprecated code will remain unchanged. We're still figuring out how to deprecate
Validated
nicely, and plan a migration plan. This can potentially be partially be automated as well. We want everything to be as automatic, and as painless as possible.
Hope that makes sense, and exciting that you'll give Arrow a shot. Be sure to ask any questions if you have any and there is also #arrow which is a bit more active if you're interested. It's a gem of information, and a great place to search.
View count: 4