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

    Jonathan Olsson

    11/11/2022, 3:17 PM
    Has the
    let
    function always been callable on nullable types (ie not
    <T : Any>
    )? I could have sworn that the following didn't use to work:
    fun foo(s: String?) {
        s.let { } // <- expected I had to do s?.let { }
    }
    Has it always worked like this or was this changed at some point?
    k
    k
    • 3
    • 4
  • s

    Szymon Jeziorski

    11/11/2022, 7:40 PM
    Hi guys, I don't quite understand some use cases of generics within stdlib and how they work. Example:
    public inline fun <R, T : R> Result<T>.getOrElse(onFailure: (exception: Throwable) -> R): R
    From the signature I would think that since
    T
    is of type
    R
    or its subtype, on
    Result<SubClass>
    instance I could invoke
    getOrElse
    only by passing lambda returning value of type which is super type to
    SubClass
    . Below code compiles perfectly fine, and I'm not sure why:
    val x: Result<CharSequence> = runCatching { "string value" }
    
    val z = x.getOrElse { 123 }
    it would be logical for me that only lambdas returning super type of
    CharSequence
    should be accepted, but I can pass whatever return type I want and this still works fine, it just makes inferred type of
    z
    Result<Any>
    . Am I missing something or should this not be expected behavior? Also, I cannot understand reason behind
    T : R
    within function's declaration, if anything
    R : T
    would be more logical to my understanding.
    e
    • 2
    • 4
  • m

    Marc Knaup

    11/12/2022, 12:06 AM
    Anyone got an idea how to make this work? Basically the function’s type parameter
    Interface
    needs to be a supertype of the class’s type parameter
    Implementation
    .
    l
    y
    • 3
    • 3
  • r

    Racci

    11/12/2022, 8:42 AM
    What is the use of providing named parameters in lambda types, this doesn't get used instead of 'it' so what is the actual use here, am i missing something?
    l
    n
    r
    • 4
    • 12
  • e

    elect

    11/12/2022, 9:16 AM
    I found myself a couple of time in the case where, given a list of string, I want to drop everything until a specific line, including the line itself, that is
    dropWhile { it != line }.drop(1)
    Is there a better way to do this?
  • h

    hfhbd

    11/12/2022, 1:54 PM
    Is there any possiblity to smartcast/return the same subtype of a sealed class when using it as receiver and when?
    sealed class F {
      object A: F()
      object B: F()
    }
    fun F.foo(): F = when (this) {
      is F.A -> F.A
      is F.B -> F.B
    }
    val a: F.A = F.A.foo() // not possible without a cast
    r
    y
    • 3
    • 9
  • e

    elect

    11/12/2022, 2:33 PM
    no
    note
    tag in kdoc?
  • y

    y

    11/12/2022, 5:25 PM
    coming from Rust: does Kotlin
    sequence
    have an equivalent of Rust’s
    .next()
    for `Iterator`s, which (lazily) returns the next item in the sequence if there is one, or
    null
    otherwise?
    c
    r
    y
    • 4
    • 20
  • d

    Darryl Pierce

    11/12/2022, 7:24 PM
    Hi, all. Im’ pretty new to using Kotlin. I’m looking for a good tutorial for how to build a cross-platform (iOS, Android) user interface for an app I’m tinkering with. Any suggestions?
    s
    • 2
    • 2
  • p

    Paul Doolittle

    11/12/2022, 8:14 PM
    Hello, I am just starting to learn Kotlin and am practicing on Intellij - I am trying to make Dog objects from a class and am having a horrible time trying to figure out how to use fun main() with the class declaration. Would someone explain to me please where I put the class methods and properties etc. when I using main(). I know there must be some logic behind this but I am tired of getting "Expecting member declaration". I would appreciate any help!
    j
    s
    • 3
    • 3
  • j

    janvladimirmostert

    11/12/2022, 9:01 PM
    since extension functions aren't allowed on enum entry names, what is the better approach to implement this?
    @Suppress("EnumEntryName")
    enum class ConfigUri(val raw: String) {
    
    	login("/login"),
    	logout("/logout"),
    	register("/register"),
    	verify("/verify/{hash}"),
    	reset1("/reset"),
    	reset2("/reset/{hash}")
    	;
    
    	fun verify.build(hash: String): String = raw.replace("{hash}", hash)
    
    }
    in the endpoints where I declare the GET / POST handlers, I want to be able to do
    GET(ConfigUri.login.raw)
    and in places where I need to fill in the hashes for example when sending out an email with a verify link, I want to be able to do
    ConfigUri.verify.build(hash = generatedRandomHash)
    to generate something like
    /verify/12344-1324234-sdfsdfs
    b
    • 2
    • 2
  • a

    Aj0y

    11/13/2022, 2:17 PM
    Hi all, any one having trouble building/running the default hello world sample code, created by Intellij when creating a kotlin project?
  • a

    Aj0y

    11/13/2022, 2:23 PM
    In my installation, java hello world sample is running right of the bat as it, while kotlin sample hello world is complaining "No JDK Specified". i checked Project Structure, things seemed ok there. What could be wrong?
  • a

    Aj0y

    11/13/2022, 2:28 PM
    Resolved, but the default sample code project seems to have set the default sdk as "Kotlin SDK" in Project Settings. After changing it to the JDK in project settings the program is compiling and running.
  • a

    Aj0y

    11/13/2022, 2:29 PM
    Shouldnt the setting be JDK by default than "Kotlin SDK", as this could be confusing to people...
  • a

    Aj0y

    11/13/2022, 2:31 PM
    Is there really a Kotlin SDK now or is it only the Kotlin Plugin? But some places in the IDE like the Project Structure seems to still refer to a 'Kotlin SDK'.
  • e

    Ellen Spertus

    11/13/2022, 5:12 PM
    Is it possible to create an extension function on functions?
    n
    j
    +2
    • 5
    • 14
  • d

    Darryl Pierce

    11/13/2022, 5:21 PM
    Hi, all. I’m starting work on an app, targeting iPads and Android tablets. My question is with dependency injection. I have a service class (OPDSLibraryService) that I would like to have automatically injected into other classes as needed, similar to how Spring’s @Autowired works. Is that an option working with Kotlin and KMM and, if so, can someone point me to a tutorial on how to get that working?
    u
    • 2
    • 2
  • b

    Ben Woodworth

    11/13/2022, 9:57 PM
    Should this be allowed? It does compile fine if I remove the type annotation from
    acceptsString
    I want to say
    R
    can be constrained to
    String
    by the smart cast but I'm not sure.
    interface Accepts<in T> {
        fun accept(value: T)
    }
    
    object AcceptsString : Accepts<String> {
        override fun accept(value: String) = println(value)
    }
    
    fun <R> example(providesR: () -> R, acceptsR: Accepts<R>) {
        if (acceptsR is AcceptsString) { // so R must be String
            val acceptsString: AcceptsString = acceptsR
            val providedR = providesR()
    
            acceptsString.accept(providedR)
            //                   ^^^^^^^^^ Type mismatch.
            //                             Required: String
            //                             Found: R
        }
    }
    d
    • 2
    • 9
  • y

    y

    11/14/2022, 9:20 AM
    if I’ve got a function with a
    List<String>
    , can I expect Kotlin to reuse this list, or will it allocate on every call to the function?
    j
    l
    +4
    • 7
    • 20
  • l

    LIRAN Y

    11/14/2022, 11:05 AM
    Hi 🙂 kind of new in Kotlin i am using the https://github.com/fabric8io/kubernetes-client and i trying to create a fun to wait until all pods are ready so i first took all the names of the pods
    private fun printAllPodsName() {
        val podList = client.pods().inNamespace("default").list()
        podList.items.forEach(Consumer { obj: Pod ->
            println(obj.metadata.name)
        })
    }
    now i want to go over this pod name list so it will check if the status is ready or not i tried to do something like this
    fun waitUntilAllPodsAreReady() {
            for (podname in printAllPodsName().toString()) {
                client.pods().inNamespace("default").waitUntilCondition({ pods ->
                    pods.status != null && pods.status.conditions != null
                }, 10, TimeUnit.MINUTES)
                println(podname.toString())
            }
        }
    but it seems like not working any idea will be blessed
    r
    n
    • 3
    • 6
  • s

    Shumilin Alexandr

    11/14/2022, 1:15 PM
    Hi all! please tell me why? Spring Boot Applcation Main class (for start) can not start, application
    @SpringBootApplication
    class ApiApplication {
    
        fun main(args: Array<String>) {
            runApplication<ApiApplication>(*args) {
                setBannerMode(Banner.Mode.OFF)
            }
        }
    }
    and this work! why?
    @SpringBootApplication
    class ApiApplication {
    
        companion object {
            @JvmStatic
            fun main(args: Array<String>) {
                SpringApplication.run(ApiApplication::class.java, *args)
            }
        }
    
    }
    k
    v
    • 3
    • 5
  • r

    rednifre

    11/15/2022, 10:53 AM
    Is there a difference between an enum and a sealed interface that only contains objects? I wonder if sealed classes/interfaces make enums obsolete.
    j
    e
    +2
    • 5
    • 18
  • n

    Nuru Nabiyev

    11/15/2022, 2:01 PM
    Can someone explain why kotlin compiler (or ide?) differentiates between these types of bugs? This was a problem for us
    s
    s
    • 3
    • 3
  • y

    y

    11/15/2022, 2:12 PM
    is it possible to make a class property that only the class itself can mutate, but is public to other classes? without making a getter? I expected
    private set
    to do this, but it seems like I can still mutate the value from outside the class.
    s
    s
    +2
    • 5
    • 20
  • x

    xun su

    11/15/2022, 2:17 PM
    Hi, is there some way we can define a variable with "-" ? sometimes json data from request may has some field name with "-", how to defined a correspond variable in data class ? the json data could be
    { "refresh-token" : "some thing" }
    I got error like this:
    l
    e
    • 3
    • 5
  • l

    LIRAN Y

    11/15/2022, 4:29 PM
    Hi i am trying to use this fun to run a linux command inside a k8s pod using fabric8io kubernetes client
    fun execIntoContainer(podName: String, containerId: String, cmd: String) : String {
        val future = CompletableFuture<Int>()
        val listener = CompletableExecListener(future)
        val out = ByteArrayOutputStream()
        val error = ByteArrayOutputStream()
        val command = cmd.split(" ").toTypedArray()
        val exec = kubernetesClient.pods().withName(podName).inContainer(containerId)
            .writingOutput(out)
            .writingError(error)
            .usingListener(listener)
            .exec(*command)
        future.get(10, TimeUnit.SECONDS)
        exec.close()
        if (error.toString().isEmpty()) {
            return out.toString()
         }
            throw RuntimeException("Error from pod: $error")
        }
    it seems works just for one command. when i add a grep for example (ls -ltr | grep t) it gave me an error and seems like the issue is with the split part
    cmd.split(" ").toTypedArray()
    org.opentest4j.AssertionFailedError: Unexpected exception thrown: java.lang.RuntimeException: Error from pod: ls: cannot access '|': No such file or directory
    ls: cannot access 'grep': No such file or directory
    ls: cannot access 't': No such file or directory
    any idea how can i use the split?
    s
    • 2
    • 2
  • g

    Gavin Ray

    11/15/2022, 7:26 PM
    How can I get around
    Overload resolution ambiguity
    for a function that has two
    varargs
    single-argument signatures?
    Overload resolution ambiguity. All these functions match.
    public open fun <T : Any!> array(vararg values: TypeVariable(T)!): Field<Array<(out) TypeVariable(T)!>!> defined in org.jooq.impl.DSL
    public open fun <T : Any!> array(vararg fields: Field<TypeVariable(T)!>!): Field<Array<(out) TypeVariable(T)!>!> defined in org.jooq.impl.DSL
    It works in Java, but not in Kotlin. I can't use
    null
    or `emptyArray()`/`emptyList()` because that produces the wrong results =/
    e
    • 2
    • 2
  • a

    Anouar di Kali

    11/16/2022, 12:50 AM
    hello , how do I contribute to kotlin projects on GitHub without building or running tests on my local machine ? especially when I have to make sure my code does not beak anything else ?
    k
    h
    +2
    • 5
    • 12
  • p

    Panos

    11/16/2022, 7:50 PM
    Hello, I’m trying to use
    limitedParallelism
    on Dispachers.IO but it is nowhere to be found despite me being on kotlinx coroutines 1.6.4. Am I missing something?
    s
    • 2
    • 1
Powered by Linen
Title
p

Panos

11/16/2022, 7:50 PM
Hello, I’m trying to use
limitedParallelism
on Dispachers.IO but it is nowhere to be found despite me being on kotlinx coroutines 1.6.4. Am I missing something?
s

Sidney Beekhoven

11/17/2022, 12:58 PM
Seems to be still experimental and requires opt in (https://kotlinlang.org/docs/opt-in-requirements.html)
View count: 10