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

    dave08

    02/14/2023, 12:15 PM
    Just watched your video on the Ktor + Arrow example @simon.vergauwen, it was one of the clearest explanations I saw! What got me really afraid was all the complex utility functions in that project... like TestResource and the Kotest integration... I was wondering if all that could be pulled out into some libraries that could be re-used? Also, wondering why if anyways you're using interfaces (when not using context receivers), why not just use the
    class Foo : IFoo
    instead of
    fun Foo() = object : Foo
    ?
    s
    e
    i
    • 4
    • 38
  • d

    dave08

    02/16/2023, 12:08 PM
    Little thought that probably wouldn't happen... if Kotlin ever decided to let
    ?.
    and
    ?:
    be overridable operators for a non-null type... then it could avoid all the `bind()`s and `flatMap`s and hacks that Arrow is doing... did someone ever propose such a thing? (or maybe some similar operator if people might find it too confusing and think that they're dealing with nullables.)
    s
    • 2
    • 9
  • j

    João Gabriel Zó

    02/16/2023, 5:23 PM
    I have a function which makes an external call and returns nothing, but I need to do something based on if it succeeded or not. Is returning
    Result<Unit>
    the best thing to do here or is there anything else in the std library?
    w
    a
    s
    • 4
    • 5
  • d

    dave08

    02/20/2023, 10:43 AM
    @simon.vergauwen It seems like Ktor uses
    Runtime.getRuntime().addShutdownHook(hook)
    , is that only SIGINT? It seems like in your video it was clearly using SIGINT, but in my current version not...
    s
    • 2
    • 8
  • m

    Mazhar Ibna Zahur

    02/23/2023, 10:58 AM
    how can i get the stacktrace of an error in functional style? throwing exception is not a right thing in FP.
    t
    s
    w
    • 4
    • 8
  • n

    Norbi

    02/25/2023, 9:16 AM
    Recently I've become a fan of explicit error handling using Result<V, E> (using https://github.com/michaelbull/kotlin-result). Yesterday I was shocked by the thought that handling errors this way somehow reminds me of Java's checked exceptions, with different syntax 😐 Is this analogy really correct? EDIT: I know that in Java some things are not possible like nice chaining of function calls. But in Kotlin it would be possible because of the language's "almost everything is an expression" paradigm.
    r
    s
    t
    • 4
    • 18
  • n

    Norbi

    03/01/2023, 9:26 AM
    I'm experimenting with Arrow's
    raise()
    functionality and I try to find a library function similar to the following hypothetical
    orElse()
    :
    context(Raise<String>)
    fun f1() = 1
    
    context(Raise<String>)
    fun f2(): Nothing = raise("error")
    
    suspend inline fun <R, A> Effect<R, A>.orElse(noinline block: suspend (R) -> A) =
        fold(
            recover = block,
            transform = ::identity
        )
    
    val v1 = effect { f1() }.orElse { 33 }
    assertEquals(1, v1)
    
    val v2 = effect { f2() }.orElse { 33 }
    assertEquals(33, v2)
    I use arrow 1.1.6-alpha.36. Thanks.
    s
    • 2
    • 6
  • k

    Kristian Nedrevold

    03/07/2023, 9:18 PM
    I have been writing a lot of Scala 3 recently and it really has made me wish Kotlin had a bit less brackets! Kotlin feels so noisy now. Especially when writing in a functional style
    r
    k
    • 3
    • 5
  • d

    dori

    03/10/2023, 10:24 AM
    Anyone here doing functional Kotlin on Android? I am interested to hear what wider architecture you are using.
    s
    • 2
    • 1
  • j

    jean

    03/17/2023, 11:26 AM
    Is there a preferred way to approach companion function with a functional style ?
    data class SomeData(val someValue: String) {
      companion object {
        fun someFunction() {}
      }
    }
    
    // OR
    
    data class SomeData(val someValue: String) {
      companion object
    }
    
    fun SomeData.Companion.someFunction() {}
    s
    • 2
    • 4
  • j

    João Gabriel Zó

    03/17/2023, 6:00 PM
    I have 2 functions which return Results.
    functionOne: Result<Something>
    functionTwo: Result<Unit>
    I’ll only call functionTwo if the first one returns a Success, and return a
    Result<Something>
    in case both of them return a Success. What’s the best way to do it using std lib? I thought the nested folds and maps and ifs turned out a bit ugly
    e
    e
    p
    • 4
    • 8
Powered by Linen
Title
j

João Gabriel Zó

03/17/2023, 6:00 PM
I have 2 functions which return Results.
functionOne: Result<Something>
functionTwo: Result<Unit>
I’ll only call functionTwo if the first one returns a Success, and return a
Result<Something>
in case both of them return a Success. What’s the best way to do it using std lib? I thought the nested folds and maps and ifs turned out a bit ugly
f1().map { something ->
  f2().map { it }
  something
}
will it work?
e

Emil Kantis

03/17/2023, 6:16 PM
no, result of line 2 is always ignored
f1().mapCatching { t ->
      f2().onFailure { throw it}
      t
   }
might be easiest
j

João Gabriel Zó

03/17/2023, 6:30 PM
alright, thanks!
e

ephemient

03/18/2023, 6:09 AM
if you were to write it without
Result
, it would look like
run {
    val x = f1()
    f2()
    x
}
(or something simpler like
f1().also { f2() }
)
with
Result
, you just translate that to include monadic bind, e.g. `.getOrThrow()`:
runCatching {
    val x = f1().getOrThrow()
    f2().getOrThrow()
    x
}
(or
runCatching { f1().getOrThrow().also { f2().getOrThrow() } }
)
if you were using #arrow's Either instead of kotlin.Result then
either {
    val x = f1().bind()
    f2().bind()
    x
}
(or the short version) is the intended usage: https://arrow-kt.io/docs/patterns/monad_comprehensions/
p

pakoito

03/20/2023, 10:04 AM
one().flatMap { it -> two.map { it } }
which is what
flatTap
does in Arrow
View count: 7