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

    Rahul Chaudhary

    02/17/2022, 9:29 PM
    Hey everyone, I am new and I have a question regarding Google's new OS fucschia, How do you see Kotlin stacking up then? Google will try to push its own stuff like dart flutter golang etc isn't it? I am confused of Kotlin will make sense to put lot of effort?
    l
    t
    +4
    • 7
    • 30
  • w

    Wolfgang

    02/18/2022, 1:42 AM
    Please anyone know any resource to learn DS and algorithm with Kotlin
    r
    • 2
    • 2
  • t

    Tim Malseed

    02/18/2022, 2:40 AM
    I’m trying to track down an unexpected inequality between two objects, and trying to figure it out by looking at the fields manually is a little tedious
    m
    • 2
    • 2
  • k

    Kiki Abdullah

    02/18/2022, 9:11 AM
    I try to create a function to identify data types
    fun <T> checkType(args: T): String {
        return when(args) {
            Int -> "Yes! it's Integer"
            String -> "Yes! it's String"
            Boolean -> "Yes! it's Boolean"
            Double -> "Yes! it's Double"
            listOf<Any>() -> "Yes! it's List"
            mapOf<Any, Any>() -> "Yes! it's Map"
            else -> "Can't identify"
        }
    }
    But, when I call this function like
    checkType("I have 3 cats")
    the output always display
    "Can't identify"
    . What's wrong with my logic? Thanks in advance
    😒olved: 2
    d
    s
    +2
    • 5
    • 15
  • s

    Sean Proctor

    02/18/2022, 9:43 AM
    I'm currently porting a desktop application that uses
    java.util.prefs.Preferences
    to Kotlin. Does anyone know of a decent wrapper to
    Preferences
    or a Kotlin alternative? russhwolf/multiplatform-settings adds suspend/flow wrappers. I'm looking for an easy way to get/put lists, maps, and objects to preferences. Android has really polluted the Kotlin search space. 90% of the results are talking about SharedPreferences or DataStore.
    • 1
    • 1
  • k

    Karlo Lozovina

    02/18/2022, 9:28 PM
    Why does this code
    (1..10).forEach {
                println(it)
                return@forEach
            }
    print all of 10 numbers? what does even "return@forEach" mean here? It seems to work more like "continue", instead of "break"?
    b
    e
    y
    • 4
    • 7
  • a

    Advitiay Anand

    02/19/2022, 12:18 PM
    What is the use of invoke operator? Do the parentheses not conflict with any constructors? I couldn't find a lot of context and examples online. Thank you to whoever can explain :)
    v
    y
    +2
    • 5
    • 15
  • h

    hfhbd

    02/19/2022, 12:47 PM
    kt
    val m: Map<String, Int> = mapOf("a" to 42, "b" to null).filterValues { it != null }
    Any possibility to infer the not null type by the compiler? Workaround is a manual cast
    s
    v
    • 3
    • 6
  • a

    Alexander Maryanovsky

    02/19/2022, 1:12 PM
    Given a function with a default argument, is there a way to call it with its default argument? I want to write a wrapper function for it while preserving the default argument value. Basically this, but without the if
    fun foo(arg1: Int, arg2: Int = 42){ ... }
    
    fun wrapper(arg1: Int, arg2: Int? = null){
        if (arg2 == null)
            foo(arg1)
        else
            foo(arg1, arg2)
    }
    s
    e
    • 3
    • 4
  • y

    Youssef Shoaib [MOD]

    02/19/2022, 1:59 PM
    Is there a way to initialize a delegated property in the same line? For instance:
    fun main() {
        val test by MyCustomDelegate() = 5 //doesn't work
        test = 5 //This is the current workaround
    }
    I don't want to change the implementation of MyCustomDelegate per se, I just want to call its setter in line. Is that currently possible?
    e
    • 2
    • 4
  • n

    Nat Strangerweather

    02/19/2022, 6:02 PM
    Hi, I'm trying to get 49 tiles from the "letterBag" to put in a grid. I'm not sure what I'm doing wrong; there are two "y"s and I got three in my grid. Any ideas? Code in thread.
    j
    • 2
    • 4
  • a

    Alderson Elliot

    02/20/2022, 8:34 AM
    Kotlin Flow have pipe like rxjs sample? https://rxjs.dev/api/operators/sample
    s
    • 2
    • 10
  • l

    Lokik Soni

    02/20/2022, 4:23 PM
    Hi all, Is it possible to use cold flow builder with Broadcast receiver. Currently I am doing my job with the help of hot flow MutableSharedFlow. But I do not want to use it*.* To see full code see in thread.
    n
    • 2
    • 2
  • k

    Karlo Lozovina

    02/21/2022, 12:33 AM
    is there anything in the stdlib to take a BlockingQueue and for-loop over it in a blocking fashion? Like take() would do, blocking when the queue is empty?
    y
    • 2
    • 1
  • m

    Mark

    02/21/2022, 9:18 AM
    Is there a nicer way to write
    val lambda = if (myClickHandler == null) null else {
        myClickHandler::onClick
    }
    I wish this was possible:
    myClickHandler?::onClick
    j
    y
    • 3
    • 21
  • j

    Jason5lee

    02/21/2022, 3:55 PM
    When I’m using
    gradle run
    ,
    readlnOrNull
    immediately returns null without reading any input. How to fix it?
    s
    e
    k
    • 4
    • 4
  • h

    harry.singh

    02/21/2022, 5:22 PM
    Just tried making the
    main
    function
    private
    in a kotlin file and it is still executable. How does JVM access the function if it is
    private
    and make it executable?
    r
    k
    j
    • 4
    • 17
  • h

    hfhbd

    02/21/2022, 7:25 PM
    Why is this not possible:
    fun interface A {
        fun foo(b: Int = 42) // Single abstract member cannot declare default values
    }
    u
    j
    • 3
    • 8
  • t

    TwoClocks

    02/21/2022, 11:07 PM
    why is this valid
    maybeNull() ?: return
    but this isn't
    maybeNull() ?: { return }
    j
    e
    • 3
    • 55
  • m

    martmists

    02/22/2022, 12:41 AM
    If I want to run a kotlin script file from my code, what's the recommended way to do it? I've seen various repos for kotlinc wrappers, but those require the end user to have kotlinc installed an on PATH, rather than embedding the compiler in some way
    r
    • 2
    • 1
  • a

    acoconut

    02/22/2022, 8:51 AM
    Hello! Do you all use mapstruct? It’s giving us issues when we try to move from kotlin 1.4 to kotlin 1.6 and I’m wondering if the community is simply not using mapstruct or if you are and we’re just doing something wrong. If you’re not using it, do you write the mappers by hand or use something else? Thank you!
    j
    t
    • 3
    • 2
  • m

    Michael de Kaste

    02/22/2022, 9:38 AM
    what would be a nice way to implement a keyTypeMap. Something like
    Map<KClass<out T>, SomeType<T>>
    currently we are filtering from a list in multiple factories which is an O(factories * N) problem. Ideally I just want to request a class type from a map and get the correct implementation
    t
    e
    j
    • 4
    • 5
  • a

    Ahmed

    02/22/2022, 12:33 PM
    Hey guys, is there a specific naming convention for class fields which has a number in their name ?
    class Apartment ( val room1: String, val room2: String )
    j
    • 2
    • 2
  • a

    Alejandro Rios

    02/22/2022, 12:49 PM
    Hello, noob question here, under what conditions we need to use
    MyFunction.invoke()
    instead of
    MyFunction()
    ?
    j
    e
    • 3
    • 3
  • s

    smit01

    02/22/2022, 6:20 PM
    runBlocking{
    println("init")                                  
     launch{
    delay(200)                                        
    println("launch one")
    }                                                 
    println("mid")
        launch{                                           
         delay(100)
         println("launch two")                          
       }
       println("end")                                  
     }
    init
    mid
    end                                                  
    launch two
    launch one
    
    
    suspend fun cli(arg:String)=Runtime.getRuntime() .exec(arg).getInputStream().bufferedReader().readLines().forEach(::println)
    
    
    runBlocking{
       println("init")
       launch{
       cli("du -hs")
       println("launch one")
       }
    
       println("mid")
    
       launch{
       cli("ls")
       println("launch two")
       }
       println("end")
     }
    
    //optput
    init
    mid
    end
    11G     .
    launch one 
    AR 
    UB
    storage
    launch two
    In this code why in second runBlocking i am not getting output like mentioned below where du -hs takes more time compare to ls command. In first runBlocking launch one has 200 delay so first second launch runs but in second runBlocking it doesn't why? Sorry for noob question or queries but I am new to coroutines and trying to learn. init mid end AR UB storage launch two 11G launch one
    j
    • 2
    • 3
  • c

    cynth

    02/22/2022, 8:10 PM
    I want to write a wrapper client for a third-party REST service in Kotlin, and I'm looking for examples. Can anyone recommend a popular Kotlin client library that's well written? (e.g. Twitter API)
    t
    • 2
    • 2
  • a

    Ahmed

    02/23/2022, 3:34 PM
    Hey guys, I have a problem with jackson deserialization I have a model that has a field of an Enum type
    data class Person (val gender: GenderEnum)
    GenderEnum
    enum class GenderEnum(val type: Sring) {
    MALE("MALE")
    FEMALE("FEMALE")
    OTHER("OTHER")
    }
    and my api response is
    "data": { gender: "male" }
    Now, I am getting an error saying,
    Cannot construct instance of the Person class, problem: Parameter specified as non-null is null: gender
    anyone has the problem with jackson before ?
    m
    • 2
    • 1
  • m

    mcpiroman

    02/23/2022, 5:30 PM
    I see this question got not answers 😞 Is it now possible after 1.5 year?
    j
    e
    • 3
    • 11
  • s

    Stylianos Gakis

    02/24/2022, 9:20 AM
    I was looking to use the
    String.replace
    function to replace some text. Specifically there was a place where this shows:
    """
      """
    And I’d just like to replace it with:
    """
    I was looking to use a triple quote String as I really like how I don’t need to escape stuff in there because it confuses me, but then I end up in this situation where I can’t really match a “”" inside it as it closes the string 😅 Is my only solution here to not use triple quotes since I can’t escape a “”" in there probably right? With a “\”\“\”\n \“\”\“” string instead?
    s
    e
    • 3
    • 4
  • m

    Michael de Kaste

    02/24/2022, 9:52 AM
    fun main{
        val scope = getScope()
        when(scope){
            // scope not smartcast and thus error
            is DeeperScope.Impl1, is DeeperScope.Impl2 -> scope.someVar = "2" 
        }
    }
    
    interface Scope
    sealed interface DeeperScope : Scope{
        var someVar: String
        data class Impl1(override var someVar: String) : DeeperScope
        data class Impl2(override var someVar: String) : DeeperScope
    }
    fun getScope() : Scope = DeeperScope.Impl2("2")
    Why can't scope be smartcast to DeeperScope in the when? Both implementations have their common parent as DeeperScope
    e
    d
    • 3
    • 3
Powered by Linen
Title
m

Michael de Kaste

02/24/2022, 9:52 AM
fun main{
    val scope = getScope()
    when(scope){
        // scope not smartcast and thus error
        is DeeperScope.Impl1, is DeeperScope.Impl2 -> scope.someVar = "2" 
    }
}

interface Scope
sealed interface DeeperScope : Scope{
    var someVar: String
    data class Impl1(override var someVar: String) : DeeperScope
    data class Impl2(override var someVar: String) : DeeperScope
}
fun getScope() : Scope = DeeperScope.Impl2("2")
Why can't scope be smartcast to DeeperScope in the when? Both implementations have their common parent as DeeperScope
e

ephemient

02/24/2022, 11:29 AM
https://youtrack.jetbrains.com/issue/KT-1982
m

Michael de Kaste

02/24/2022, 1:15 PM
wow a 10 year old ticket for something that seems quite trivial
d

dmitriy.novozhilov

02/24/2022, 1:50 PM
Such smartcasts will be avaliable in K2 compiler
:nice: 4
View count: 7