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
getting-started
  • p

    Paulius O

    10/30/2021, 6:50 AM
    Hello I have a question about auto-formatting, Why is it that we get this uneven indentation in the following situation(where `a`’s indentation is smaller than the rest?):
    val myVal = (
        a.size +
            b.size +
            c.size)
    Is there a way to change klint settings to align it automatically? I would prefer all to be offset at the same level. If there isn’t maybe someone can explain why indentation the way that it’s working now is better?
    v
    k
    • 3
    • 9
  • a

    andylamax

    10/31/2021, 7:40 AM
    Hello there, I have a question regarding annotations. What is the difference between
    object Test {
      @get:Composable
      val primary: Color get() = TODO()
    }
    and
    object Test {
      val primary: Color
      @Composeable
      get() = TODO()
    }
    Compose seem to be happy with the later and not with former. I though these where same. Anyone?
    k
    r
    • 3
    • 13
  • s

    Seb C

    10/31/2021, 2:35 PM
    How to debug in object within intellij? break points does not seem to stop in it thanks
    r
    • 2
    • 1
  • m

    Michael de Kaste

    11/01/2021, 11:24 AM
    Is there a way to to associate an enum with a sealed class implementation? Lets say you have a generic enum accessible in your entire project (in my case I'm working with types of mental health care) and throughout your project, sometimes, per type, we need a slightly different implementation. Currently I have an Enum with Type1, Type2 and Type3, and then a sealed class with an implementation for every type. Now I have a map, in which I would like to give a key (enum) and then get back the specific implementation. However, I cannot guarantee that if you call the enummap with type1 key you get a value that represented type1 value
    j
    • 2
    • 5
  • a

    Alexander Suraphel

    11/01/2021, 2:12 PM
    What is
    R
    supposed to be set by default on this snippet?
    c
    • 2
    • 3
  • a

    althaf

    11/01/2021, 2:23 PM
    Is there an equalant way to convert this small code in RxJS to Kotlin flow I'm not really getting the way in which this java script convert the click events to an array in the map.
    var button = document.querySelector('.button');
    var label = document.querySelector('h4');
    var clickStream = Rx.Observable.fromEvent(button, 'click');
    var doubleClickStream = clickStream
      
    .bufferWhen(() => clickStream.debounceTime(250))
      
    .map(arr => arr.length)
      
    .filter(len => len === 2);
    doubleClickStream.subscribe(event => {
      
    label.textContent = 'double click';
    });
    doubleClickStream
      
    .delay(1000)
      
    .subscribe(suggestion => {
        
    label.textContent = '-';
      
    });
    r
    • 2
    • 2
  • s

    Stefan Oltmann

    11/01/2021, 3:13 PM
    I ask here because it seems like a very basic question... What can I do so that my compiled Windows EXE does not have the name "POSIX WinThreads for Windows" but a one I assign? What property do i need? This is my build.gradle.kts
    plugins {
        kotlin("multiplatform")
    }
    
    kotlin {
    
        mingwX64("native") {
            binaries {
                executable()
            }
        }
    }
    
    tasks.withType<Wrapper> {
        gradleVersion = "7.2"
        distributionType = Wrapper.DistributionType.BIN
    }
    • 1
    • 2
  • p

    PriNova

    11/02/2021, 11:23 AM
    Hello everyone, I tried the reified feature of Kotlin and was suprised, that my primitives becomes boxed. Wouldn't it make sense with inlined reified functions to have monomorphization as language feature? Here's a little example:
    fun main() {
        val value: Int = 2
        showValue<Int>(value)
    }
    
    inline fun <reified T> showValue(value: T) = println("$value")
    The decompiled Java shows that the primitive int will be boxed into an Integer. And the function-signature has an Object as parameter-type. I think, although the reified function will be inlined, that the use of primitives, or whatever object for T, stays the same, because of inlining. Is this possible? Thank you
    e
    i
    • 3
    • 6
  • m

    Marko Kunic

    11/03/2021, 4:41 PM
    a library I am using has a suspend function, I am wondering how can I get a value out of that function without actually making my function suspended?
    j
    • 2
    • 4
  • t

    Tim Abil

    11/03/2021, 5:35 PM
    Is there any difference between
    is
    operator and class comparison?
    sealed class MyClass {
        object ONE : MyClass()
        object TWO : MyClass()
    }
    
    inline fun <reified T> List<MyClass>.findClass(): T? {
        return find { it is T } as T
    }
    
    fun <T: Any> List<MyClass>.findClass(clazz: KClass<T>): T? {
        return find { it::class == clazz } as T?
    }
    e
    c
    • 3
    • 5
  • j

    Justin Tullgren

    11/03/2021, 7:10 PM
    can anyone point me to how to use the
    Deprecated
    annotation
    ReplaceWith
    when the argument is a receiver function type?
    @Deprecated
    fun factory(initializer: Builder.() -> Unit): Type = Builder().apply(initializer).build()
    j
    • 2
    • 11
  • m

    Marko Novakovic

    11/04/2021, 9:58 AM
    I don’t see it at all but what about nesting related functions? instead of having a lot private functions that are called from only one place those functions can be nested inside function that actually need them. make them lambdas also works… what are your thought/experiences?
    j
    k
    s
    • 4
    • 4
  • c

    Christopher Stocks

    11/04/2021, 3:29 PM
    Could anyone point me towards a method/library for handling navigation within Compose for Desktop?
    t
    • 2
    • 1
  • j

    Jilles Soeters

    11/04/2021, 3:51 PM
    Any good articles describing wrting your own DSL? I know there is a good book out there but I have too much books on my TO_READ list already
    k
    c
    • 3
    • 3
  • u

    ursus

    11/04/2021, 7:21 PM
    Hey, is there a way to generally reference the value inside a value class? I'm trying to use type-safe database ids, and therefore I need a column adapter
    class BusinessMessageIdColumnAdapter : ColumnAdapter<BusinessMessageId, String> {
        override fun decode(databaseValue: String): BusinessMessageId = BusinessMessageId(databaseValue)
        override fun encode(value: BusinessMessageId): String = value.value
    }
    for every type of id, which is annoying I know I could get it via reflection, but .. probably looking for a "hack" like this (the enumValues function)
    @Suppress("FunctionName") // Emulating a constructor.
    inline fun <reified T : Enum<T>> EnumColumnAdapter(): EnumColumnAdapter<T> {
      return EnumColumnAdapter(enumValues())
    }
    e
    j
    • 3
    • 16
  • k

    KV

    11/05/2021, 8:06 PM
    Hey, Have a question: I am using MVVM pattern in the app & my approach is: After button click, open a new fragment/class, call viewmodel, call APIs from the server (usecase, repo & repo impl part), and the result would we shown to UI (fragment) after observing the data. So is there any way that after button click, call the API and based on the response of the API, show updated UI in the fragments. Does anyone know how to achieve this kind of behaviour in our android application?
    a
    • 2
    • 4
  • e

    elect

    11/05/2021, 9:20 PM
    why Idea is converting a functional java interface with the same
    @FunctionalInterface
    in the first case and
    fun interface
    in the second case here? What's the different between the annotation and
    fun interface
    ?
    s
    • 2
    • 1
  • l

    Lokik Soni

    11/06/2021, 12:58 PM
    Hello everyone this is my first question in slack i.e I want to perform some operations on data class fields before accessing them to UI. For ex from Broadcast receiver I am passing battery temperature to the data class but the passed temperature format is not required by UI so i want to add logic to convert temperature from kelvin to celsius and hide the kelvin field from UI.
    data class BatteryProfile(
        private val _temperature: Int,
    ) {
        val temperature get() = logic to convert _temperature from kelvin to celsius
    
    }
    So i applied the above solution but i am feeling it is not good way also I have not seen data class primary constructor field as privete in any example. Please tell me if it is correct way or if wrong so how to achieve this.
    s
    • 2
    • 1
  • a

    Ansh Tyagi

    11/07/2021, 7:42 AM
    hey everyone so i was trying to add a java(ant) proj to a kotlin(gradle) proj as a subproj so that i could import it in some Kotlin class? The current file structure is something like this:
    .
    ├── build.gradle.kts
    ├── src
    ├── settings.gradle.kts
    └── JavaProj(ant)
        ├── ant.settings
        └── build.xml
    i hope i could make this file stucture clear. but the issue is i could not import the java proj in the kotlin. I think its something realted to including the proj in settings.gradle.kts but searching stackoverflow wasnt enough. Is there something else i ned to do as well while importing another subproj?
    r
    v
    • 3
    • 13
  • a

    Alexander Suraphel

    11/07/2021, 2:41 PM
    Is there a common ancestor for
    String
    and
    Char
    ?
    r
    e
    • 3
    • 2
  • a

    Alexander Suraphel

    11/07/2021, 2:46 PM
    When creating generic function what is the difference between
    *fun* <T : Comparable<T>>
    and
    *fun* <Comparable<T>>
    ?
    r
    • 2
    • 4
  • m

    Martin Barth

    11/08/2021, 10:23 AM
    In a when block I have a lot of code like that:
    "-" -> if (aggregate is Minus) Minus(*aggregate.expressions, nextExpression) else Minus(aggregate, nextExpression)
                            "+" -> if (aggregate is Plus) Plus(*aggregate.expressions, nextExpression) else Plus(aggregate, nextExpression)
    ....
    I wanted to make that easier, but i am failing. My Idea was something like this:
    private inline fun <reified T> myIdea(aggregate: InfixExpression, nextExpression: Expression): T = if (aggregate is T) 
                T(*aggregate.expressions, nextExpression)
            else
                T(aggregate, nextExpression)
    using the Type T as a Constructor does not work. Any advice?
    m
    v
    c
    • 4
    • 3
  • d

    David Lax

    11/09/2021, 3:47 AM
    Hi Guys, any recommendation for GraphQL client library?
    p
    s
    • 3
    • 3
  • s

    smit01

    11/09/2021, 6:52 AM
    In kotlin for now fun <T> T.foo(block:(T)->Unit):Unit = block(this) here type parameter T is nullable why not make it not-nullable implicitly?
    a
    • 2
    • 1
  • a

    Arpit Shukla

    11/09/2021, 10:23 AM
    What’s the difference between these two ways of exposing MutableStateFlow as StateFlow?
    private val _data = MutableStateFlow(0)
    1. val data: StateFlow<Int> = _data
    2. val data = _data.asStateFlow()
    In other words, what does
    asStateFlow()
    do?
    b
    k
    • 3
    • 3
  • r

    Robert Jaros

    11/09/2021, 12:46 PM
    Is this normal? The url https://plugins.gradle.org/m2/org/jetbrains/kotlin/kotlin-gradle-plugin-api/1.5.31/kotlin-gradle-plugin-api-1.5.31.pom redirects to https://jcenter.bintray.com/org/jetbrains/kotlin/kotlin-gradle-plugin-api/1.5.31/kotlin-gradle-plugin-api-1.5.31.pom and the SSL certificate on jcenter.bintray.org has expired. I can't build any Kotlin project.
    👀 1
    s
    • 2
    • 6
  • j

    jeggy

    11/09/2021, 1:23 PM
    How come Kotlin contracts are not working anymore? These have been working fine a few months back.
    r
    e
    • 3
    • 3
  • n

    Nikolay Lebedev

    11/09/2021, 1:41 PM
    Hi! How do I merge two JsonElement objects into one? I have
    {"name": "Foo"}
    and
    {"age": 42}
    and want to get
    {"name": "Foo", "age": 42}
    object.
    p
    • 2
    • 1
  • d

    dave08

    11/09/2021, 2:32 PM
    Why aren't
    data
    and
    inner
    modifiers to
    class
    compatible together?
    j
    e
    • 3
    • 6
  • m

    Michael Clancy

    11/09/2021, 3:18 PM
    Hi there, I am looking to apply a computationally expensive transformation to items in a flow, emitting intermediate signals indicating the progress of this transformation. (Emitting multiple times from .transform). If certain error conditions are met during this transformation, I want to skip the rest of the function being applied, and move onto the next item in the flow.
    someFlow.transform {
    if (someCondition) {
    emit(Resource.Loading(someIntermediateResult))
    } else {
    emit(Resource.Error("Couldn't compute")
    //Want to place something here to skip code below and move to next item in flow
    }
    emit(Resource.Success(finalResult)
    Any ideas? Feel like I am missing something simple Thanks, Michael
    e
    • 2
    • 2
Powered by Linen
Title
m

Michael Clancy

11/09/2021, 3:18 PM
Hi there, I am looking to apply a computationally expensive transformation to items in a flow, emitting intermediate signals indicating the progress of this transformation. (Emitting multiple times from .transform). If certain error conditions are met during this transformation, I want to skip the rest of the function being applied, and move onto the next item in the flow.
someFlow.transform {
if (someCondition) {
emit(Resource.Loading(someIntermediateResult))
} else {
emit(Resource.Error("Couldn't compute")
//Want to place something here to skip code below and move to next item in flow
}
emit(Resource.Success(finalResult)
Any ideas? Feel like I am missing something simple Thanks, Michael
e

ephemient

11/09/2021, 7:51 PM
return@transform
will exit the lambda expression early
❤️ 1
m

Michael Clancy

11/10/2021, 9:30 AM
Thank you!
View count: 2