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
announcements
  • h

    hhariri

    01/27/2021, 12:52 PM
    https://twitter.com/kotlinconf/status/1354403313647759360?s=09
    ❤️ 3
    😢 20
    🦾 2
    s
    • 2
    • 1
  • b

    Big Chungus

    01/27/2021, 5:29 PM
    Is there any kotlin-first json path library out there?
    m
    c
    r
    • 4
    • 10
  • r

    rajesh

    01/28/2021, 7:45 AM
    Seeking for advice here. My workflow is as below: Mobile app send photo/video to spring boot backend, spring boot upload it to cloud object storage and add metadata to database. Question is: While spring boot is uploading file to cloud, how to respond mobile client immediately and notify them about upload success? I thought of creating work request and let client poll it.
    f
    • 2
    • 2
  • u

    user

    01/28/2021, 8:00 AM
    message has been deleted
    j
    • 1
    • 1
  • l

    Leon K

    01/28/2021, 11:13 AM
    Is it possible to make @Nullable annotations in libraries currently not understood by the kotlin nullabillity annotation magic count as nullable values somehow? For context, im using a library that defines its own @nullable, and id like kotlin to consider that annotation such that my calls to annotated functions from that library are properly detected as returning nullable values. Ive looked at the JSR305 compiler flag thingy, but im not sure if thats actually what i need here - at least it doesnt do anything, and im unsure how kotlin would know if the specified annotation is supposed to mean non-null or nullable
    a
    e
    • 3
    • 5
  • s

    stefandekanski

    01/28/2021, 12:50 PM
    This works :
    fun <T, M : MutableCollection<T>> Collection<T>.partitionTo(left: M, right: M, predicate: (T) -> Boolean): Pair<Collection<T>, Collection<T>> {
        forEach {
            if (predicate(it)) left += it else right += it
        }
        return Pair(left, right)
    }
    so as this:
    fun <T, C : Collection<T>, M : MutableCollection<T>> C.partitionTo(left: M, right: M, predicate: (T) -> Boolean): Pair<Collection<T>, Collection<T>> {
        forEach {
            if (predicate(it)) left += it else right += it
        }
        return Pair(left, right)
    }
    This doesn’t compile… why?
    fun <T, C : Collection<T>, M : MutableCollection<T>> C.partitionTo(left: M, right: M, predicate: (T) -> Boolean): Pair<C, C> {
        forEach {
            if (predicate(it)) left += it else right += it
        }
        return Pair(left, right)
    }
    when you cast it, then i works then but it’s unsafe cast..
    fun <T, C : Collection<T>, M : MutableCollection<T>> C.partitionTo(left: M, right: M, predicate: (T) -> Boolean): Pair<C, C> {
        forEach {
            if (predicate(it)) left += it else right += it
        }
        return Pair(left as C, right as C)
    }
    Why can’t typesystem figure out that M is covariant towards C ?
    s
    y
    • 3
    • 3
  • y

    Youssef Shoaib [MOD]

    01/28/2021, 3:42 PM
    The
    ifEmpty
    extension function on String is defined like this in the Kotlin stdlib:
    public inline fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : CharSequence, C : R =
        if (isEmpty()) defaultValue() else this
    However, if you try to define exactly the same function in your own code you get this error:
    Type parameter cannot have any other bounds if it's bounded by another type parameter
    So how is the standard library circumventing this error? I even checked and there aren't any
    @Suppress
    annotations in the file at all regarding this, so how in the world did they stop that error?
    👍 2
    a
    c
    • 3
    • 2
  • k

    Kunal Dabir

    01/28/2021, 5:40 PM
    For a kotlin code-gen tool, any recommendation for assertion library for writing expectations on generated code? I am inclining towards some kind of approval testing framework in Kotlin, any recommended testing-library? I prefer to avoid going via verifying AST nodes route as it gets very verbose. FWIW, We are using kotlinpoet to generate code.
    m
    g
    • 3
    • 15
  • m

    Manuel Dupont

    01/29/2021, 7:50 AM
    I am having a hard time.
    j
    • 2
    • 2
  • a

    alexandrepiveteau

    01/29/2021, 1:36 PM
    Is it possible to use the
    @DslMarker
    annotation on a
    suspend
    scope receiver ? I’m getting an
    java.lang.IllegalStateException: Backend Internal error: Exception during IR lowering
    exception when I write the following code, but don’t face any issue when I remove the
    suspend
    modifier :
    @DslMarker
    annotation class MyDslMarker
    
    @MyDslMarker
    interface MyDsl
    
    fun something(
        scope: suspend MyDsl.() -> Unit,
    ) {
    }
    
    fun main() {
        something { }
    }
    y
    u
    • 3
    • 7
  • k

    Karlo Lozovina

    01/29/2021, 4:52 PM
    is there a simpler example of using
    kotlinx-benchmark
    with .kts Gradle scripts? example at https://github.com/Kotlin/kotlinx-benchmark/tree/master/examples is a complex one, and trying to simplify I'm getting nowhere...
    i
    s
    • 3
    • 3
  • a

    Anarakul

    01/29/2021, 4:59 PM
    What is the appropriate channel for discussing Kotlin serialization issues?
    k
    v
    +2
    • 5
    • 10
  • g

    Gayan Perera

    01/29/2021, 7:31 PM
    Hi All, Do we have command line or java library that can be used to decompile kotlin classes ?
    u
    • 2
    • 1
  • l

    Logan Knight

    01/29/2021, 8:39 PM
    Since I have no one in house to ask this of, I'm asking here. Looking for broad strokes architectural advice. My company needs a method to create tickets from emails in a multi-tenant system. Each tenant can have multiple pop/imap servers configured. What would you recommend as a high level architecture for monitoring an arbitrary number of email servers and writing to an aws aurora db cluster?
    :google: 2
    :stackoverflow: 4
    a
    • 2
    • 2
  • f

    Florian

    01/30/2021, 3:56 PM
    I read that you shouldn't inline large functions. Is it better to not use inline here?
    inline fun <ResultType, RequestType> networkBoundResource(
        crossinline query: () -> Flow<ResultType>,
        crossinline fetch: suspend () -> RequestType,
        crossinline saveFetchResult: suspend (RequestType) -> Unit,
        crossinline onFetchSuccess: () -> Unit = { },
        crossinline onFetchFailed: (Throwable) -> Unit = { },
        crossinline shouldFetch: (ResultType) -> Boolean = { true }
    ) = flow {
        val data = query().first()
    
        val flow = if (shouldFetch(data)) {
            emit(Resource.Loading(data))
    
            try {
                saveFetchResult(fetch())
                onFetchSuccess()
                query().map { Resource.Success(it) }
            } catch (t: Throwable) {
                onFetchFailed(t)
                query().map { Resource.Error(t, it) }
            }
        } else {
            query().map { Resource.Success(it) }
        }
        emitAll(flow)
    }
    n
    h
    • 3
    • 15
  • n

    Nikita Voloshin

    01/30/2021, 4:12 PM
    Hi all, can anybody explain why Kotlin doesn't allow smart-cast on receiver after function call in infix manner? Consider this toy example:
    n
    • 2
    • 4
  • u

    ursus

    01/31/2021, 11:18 AM
    Can I compose annotations somehow? I have these two anntations everywhere
    @Provides
    @JvmStatic
    fun widgetUpdater() ..
    Can I turn it somehow to this? where
    @ProvidesAndJvmStatic
    would reference then the daggers
    @Provide
    and kotlins
    @JvmStatic
    inside?
    @ProvidesAndJvmStatic
    fun widgetUpdater() ..
    🇳🇴 2
    c
    b
    • 3
    • 8
  • o

    oday

    01/31/2021, 12:42 PM
    is there a library or an stdlib function or some way to represent trees through a print statement?
    n
    • 2
    • 2
  • s

    StragaSevera

    01/31/2021, 1:42 PM
    I'm trying to learn coroutines and I found a strange thing. If I save a reference to CoroutineScope to a field, and then a method uses this field to launch some jobs, it seems to be unable to cancel such jobs. My example has about 40 lines, I don't want to break some mobile user's screen, so it is linked here: https://gist.github.com/StragaSevera/b294625b927eb002be8987804de31013 This code should stop counting when I press "Enter", but it does not cancel the coroutines and counts forward after the "Cancelled" message 😃 Also, the bug happens if I pass the scope as an argument to the
    start()
    method, but does not happen if I remove the class and copy contents of the
    start()
    method to the
    main()
    function. It seems like there is some caching issue...
    i
    z
    y
    • 4
    • 10
  • s

    stephanmg

    01/31/2021, 3:29 PM
    Somebody has experience or a great resource how to build Kotlin Gradle project with Github Actions?
    r
    • 2
    • 21
  • r

    Rob Elliot

    01/31/2021, 7:31 PM
    Hey - my son (14, bright) is interested in spending February half term learning Kotlin. He’s basically a complete beginner programmer. We’ve found this: https://www.udemy.com/course/kotlin-course/ Any experience with it? Or other suggestions? Grateful for any feedback or thoughts. Thanks!
    🎉 4
    y
    j
    • 3
    • 5
  • d

    diniamo

    01/31/2021, 10:25 PM
    Hey, I'm new here. I'm having problems trying to use Kotlin Jsr223, it just throws an NPE on the .eval function call... any ideas? Also is this the right place to ask?
    v
    • 2
    • 27
  • j

    javaru

    02/01/2021, 2:12 PM
    Inside an extension function, how can I call another function without an implicit
    this
    being used? In my IntelliJ Plugin have this:
    fun Project.foo {
       ...
       service<SomeApplicationService>().bar()
    }
    The
    com.intellij.openapi.components.service.kt
    file has two
    service
    functions:
    inline fun <reified T : Any> service(): T = ApplicationManager.getApplication().getService(T::class.java)
    inline fun <reified T : Any> Project.service(): T = getService(T::class.java)
    Because I'm inside a
    Project
    extension function, it is implicitly calling
    this.service<SomeApplicationService>().work()
    and thus the
    Project.service()
    extension function rather than
    service()
    . I was able to workaround by creating a separate
    applicationService()
    convenience function. But I have to imagine this is not an unheard of situation and was wondering if there is some syntax to say not to use the implicit
    this
    . It's a top-level function, to I'm not aware of any
    this@
    syntax for this case.
    v
    d
    +3
    • 6
    • 80
  • f

    Florian

    02/01/2021, 3:59 PM
    I sort this list to get the smallest occurrence of a property. Is there a simpler way in Kotlin?
    val sortedArticles = cachedArticles.sortedBy { article ->
        article.updatedAt
    }
    val oldestTimestamp = sortedArticles.firstOrNull()?.updatedAt
    m
    m
    • 3
    • 4
  • k

    Karlo Lozovina

    02/01/2021, 4:42 PM
    is there a way to write
    foobar
    so that I can pass ::class of either subclasses? https://pl.kotl.in/Y5NcoKR3K
    r
    t
    • 3
    • 10
  • m

    Marko Mitic

    02/02/2021, 5:12 AM
    Did anyone make UML diagrams of Kotlin code recently? My Intellij Ultimate doesn't show relations between classes and won't create any links. I've lost half day on trying to find a tool or plugin that would either convert kotlin code to UML or edit IntelliJ's '.uml' file.
    a
    • 2
    • 2
  • m

    Mjahangiry75

    02/02/2021, 7:40 AM
    Hi all Does anyone know why
    StateFlow
    doesn't emit new changes of a
    MutableList
    ? this is my code:
    _selectedLanguages.value = _selectedLanguages.value.apply {
       if (changedLanguage.isSelected)
          add(changedLanguage)
       else
          remove(changedLanguage)
    }
    a
    g
    z
    • 4
    • 25
  • b

    Ben Butterworth

    02/02/2021, 10:36 AM
    Why is it important that extra programming features (coroutines) are added via libraries instead of the language directly? Ive heard this "benefit" of kotlin stated a few times but never really understood whats so beneficial. I can guess one benefit: a library can evolve faster than a language.
    j
    m
    +4
    • 7
    • 77
  • r

    rajesh

    02/02/2021, 4:00 PM
    How do i convert this java annotation to kotlin code
    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
    @Retention(RUNTIME)
    @Documented
    @Constraint(validatedBy = CustomerTypeSubSetValidator.class)
    public @interface CustomerTypeSubset {
    CustomerType[] anyOf();
    String *message*() default "must be any of {anyOf}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    }
    m
    t
    • 3
    • 5
  • a

    AB

    02/02/2021, 9:44 PM
    guys if I have two final classes (generated from package) of different types and they are following builder pattern and I have two other classes (generated from a package) that I want to them to be mapped to the builder classes I will map this manually, and they both have the same structure when mapping, can I have a one generic map method for both of them ?
    class Mapper
    {
    // can I have a one generic method, instead of two ??  
     like:   fun <T> MapKeyword (<U> keyword){ return T().SetId(keyword.Id).Build() }
    
    
    
      fun MapKeywordOne(KeywordOne  keywordOne) : keyWordOneBuilder  
        { return keyWordOneBuilder().SetId(keywordOne.Id).Build() }
    
       fun MapKeywordTwo(KeywordTwo  keywordTwo) : keyWordTwoBuilder  
        { return keyWordTwoBuilder().SetId(KeywordTwo.Id).Build() }
    }
    
    
    
    final class keyWordOneBuilder  // this one is from another package and I cannot modify
    {   
    setId(){ // implementation }
    build(){ // implementation }
    }
    
    final class keyWordTwoBuilder  // this one is from another package and I cannot modify
    {   
    setId(){ // implementation }
    build(){ // implementation }
    }
    
    final class KeywordOne  // this one is also sealed from a different package
    {
    public int Id;
    }
    
    final class KeywordTwo   // this one is also sealed from a different package
    {
    public int Id;
    }
    t
    a
    • 3
    • 4
Powered by Linen
Title
a

AB

02/02/2021, 9:44 PM
guys if I have two final classes (generated from package) of different types and they are following builder pattern and I have two other classes (generated from a package) that I want to them to be mapped to the builder classes I will map this manually, and they both have the same structure when mapping, can I have a one generic map method for both of them ?
class Mapper
{
// can I have a one generic method, instead of two ??  
 like:   fun <T> MapKeyword (<U> keyword){ return T().SetId(keyword.Id).Build() }



  fun MapKeywordOne(KeywordOne  keywordOne) : keyWordOneBuilder  
    { return keyWordOneBuilder().SetId(keywordOne.Id).Build() }

   fun MapKeywordTwo(KeywordTwo  keywordTwo) : keyWordTwoBuilder  
    { return keyWordTwoBuilder().SetId(KeywordTwo.Id).Build() }
}



final class keyWordOneBuilder  // this one is from another package and I cannot modify
{   
setId(){ // implementation }
build(){ // implementation }
}

final class keyWordTwoBuilder  // this one is from another package and I cannot modify
{   
setId(){ // implementation }
build(){ // implementation }
}

final class KeywordOne  // this one is also sealed from a different package
{
public int Id;
}

final class KeywordTwo   // this one is also sealed from a different package
{
public int Id;
}
t

Tyler Hodgkins

02/02/2021, 10:30 PM
You could likely make this work with
reified
and a bit of reflection magic to create an instance, but that would rely on a no-arg constructor.
a

AB

02/02/2021, 11:00 PM
thanks a lot @Tyler Hodgkins yeah, I thought of reflection, but looks like I will add more complexities to this 😄
a

ashmelev

02/03/2021, 12:28 AM
Perhaps making them both implement the same Interface and then "mapping" the Intrface would work?
t

Tyler Hodgkins

02/03/2021, 12:44 AM
AB mentioned that he doesn't own the classes
👍 1
View count: 5