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

    Ayfri

    04/05/2022, 5:25 PM
    Hi, is there any tutorial on how to work with multiple gradle modules ?
    t
    • 2
    • 29
  • j

    Jan

    04/06/2022, 3:31 PM
    Is it not possible to save a lambda parameter from a inline function to a variable? This doesn't work:
    @PublishedApi
    internal var onFinish = {}
    
    inline fun onFinish(action: () -> Unit) {
        onFinish = action
    }
    s
    e
    • 3
    • 5
  • a

    Anthony Flores

    04/06/2022, 10:13 PM
    What is the best way to compare two classes of the same type, and copy all the properties of the second one that are different compared to an original? For example, let's say I have 3 string variables stored in said class:
    class SomeClass {
        var string1: String = "Default"
        var string2: String = "Default"
        var string3: String = "Default"
    }
    and lets say in the first class,
    string1
    is "Text,"
    string2
    , is "Other Text," and in the second class
    string1
    is "String, " while
    string2
    is still Default I would want it so that the first string is "String," the second string is "Other Text," and
    string3
    as "Default"
    a
    m
    • 3
    • 6
  • m

    migueltb01

    04/07/2022, 4:41 PM
    Hello all! I want to ask if anyone knows any good resource to start with Compose/Jetpack, thanks!
    👍 1
    c
    m
    k
    • 4
    • 3
  • a

    Ahmed

    04/08/2022, 3:16 PM
    Hey guys, do we need to await for the result returned by a suspended function ?
    runblock {
    val result =  methodCall(). // this method is suspended 
    
    repository.persistResultToDB(result)
    }
    so, the
    methodCall()
    do we need to await for its completion, to be able to use the returned
    result
    to persist them to the db ?
    h
    j
    • 3
    • 5
  • j

    Jan

    04/08/2022, 4:42 PM
    Hey I was using this approach: (thread) to split my seconds into minutes and seconds. However if I get seconds > 3600 this one doesn't work anymore as seen in the picture. Anyone got a better solution?
    a
    c
    • 3
    • 10
  • m

    mikehearn

    04/11/2022, 9:37 AM
    e.g.
    fun <T> bar(): T { 
        error("")
        return "" as T
    }
    
    fun foo() {
        if (true) {
            1
        } else {
            bar()
        }
    }
    This works - bar can be invoked, because it infers to int. But if you unwrap the if statement, suddenly the return type of bar can't be inferred anymore (the contents of bar aren't important here, this crops up no matter what it contains).
    r
    a
    • 3
    • 16
  • m

    Michael de Kaste

    04/11/2022, 10:59 AM
    whats the best practice for non-spring oriented singleton retrieval if you know interface? ``````
    • 1
    • 1
  • m

    marko ziza

    04/11/2022, 4:47 PM
    Hello, I don't know how to call this Java code from Kotlin:
    public static Document parse(File file, @Nullable String charsetName) throws IOException {
            return DataUtil.load(file, charsetName, file.getAbsolutePath());
        }
    when I call this code from Kotlin,
    val document = Jsoup.parse(inputHTML, null )
    I get
    Kotlin: Null can not be a value of a non-null type String
    How can I call this with Java type null, since parameter is @Nullable and therefore Null should be accepted.
    e
    n
    • 3
    • 3
  • r

    Ruckus

    04/11/2022, 6:48 PM
    I'm messing around with the new context receivers and I'm seeing what appears to be an issue, but I figured I'd ask here to make sure I'm not just doing something wrong. (see thread)
    d
    y
    • 3
    • 5
  • j

    Jan

    04/11/2022, 7:15 PM
    Why is kotlin showing me: 1.49262774E8 and not 149,262,774?
    r
    • 2
    • 2
  • c

    Colton Idle

    04/11/2022, 10:51 PM
    If I have
    val data =
        hashMapOf(
                "firstName" to firstName,
                "lastName" to lastName)
    but I wanted to not add firstName or lastName to the hashmap if they are null. What would be the best way to do that?
    e
    j
    +2
    • 5
    • 26
  • a

    andodeki

    04/12/2022, 4:22 AM
    hey lads, can I make a for loop on a tuple of two list of the same size?? or a for loop on two sets of list
    m
    • 2
    • 1
  • p

    Pavel Matusevich

    04/12/2022, 6:29 AM
    Hi everyone! I have a rather strange situation: I am testing my library with JUnit (as it was in many guides) and they are working correctly on my local machine, but on Github Actions they fail with really strange exception:
    Caused by:
            org.opentest4j.AssertionFailedError: Array elements differ at index 0. Expected element <Lesson(place=4, timeConstraints=TimeConstraints(startHour=11, startMinute=25, endHour=12, endMinute=10), title=Биология, classID=8, teacherID=104631, journalID=null)>, actual element <Lesson(place=4, timeConstraints=TimeConstraints(startHour=11, startMinute=25, endHour=12, endMinute=10), title=Биология, classID=8, teacherID=104631, journalID=100125)>.
            Expected <[Lesson(place=4, timeConstraints=TimeConstraints(startHour=11, startMinute=25, endHour=12, endMinute=10), title=Биология, classID=8, teacherID=104631, journalID=null)]>, actual <[Lesson(place=4, timeConstraints=TimeConstraints(startHour=11, startMinute=25, endHour=12, endMinute=10), title=Биология, classID=8, teacherID=104631, journalID=100125)]>.
    The most bizzare part of that assertion fail is part with
    journalID=null
    in expected element. The problem is that there are no null journal ID's in tests. Does anybody know what is my problem? Source code for tests (the failing one is marked): https://github.com/Neitex/Schools_Parser/blob/74c9fb9ed14b47cce4d173dc288d0a91a088b3ed/src/test/kotlin/com/neitex/SchoolsByParserTest.kt#L430 Source code of Lesson constructor (this is a regular data class, nothing special): https://github.com/Neitex/Schools_Parser/blob/74c9fb9ed14b47cce4d173dc288d0a91a088b3ed/src/main/kotlin/com/neitex/DataClasses.kt#L63 Thanks in advance!
    r
    • 2
    • 4
  • r

    Ruckus

    04/12/2022, 6:47 PM
    Is there a good way to have object "inherit" each other? Explanation in thread.
    p
    y
    e
    • 4
    • 14
  • p

    poohbar

    04/12/2022, 8:50 PM
    Is there a built-in to give me stats about a collection of numbers? E.g. avg, min, max at the same time?
    h
    m
    +2
    • 5
    • 9
  • v

    Vitali Plagov

    04/13/2022, 4:03 AM
    val map = getMapOfDataFromOutside()
    val homeCountry = map["Home Country"] ?: error("Data table is missing 'Home Country' entry or its key is incorrect")
    val homeCity = map["Home City"] ?: error("Data table is missing 'Home City' entry or its key is incorrect")
    Hi. I have this map and I handle the nullable value by a key with
    ?: error(…)
    . The error message is equal for all entries I’m retrieving except one parameter, so I want to extract this into a separate method to make code shorter:
    val homeCountry = map["Home Country"] ?: throwAnErrorForKey("Home Country")
    private fun throwAnErrorForKey(key: String) {
        error("Data table is missing '$key' entry or its key is incorrect")
    }
    With this code, the return type of the
    homeCountry
    is
    Any
    and not
    String
    . How can I extract the
    ?: error()
    part properly?
    r
    • 2
    • 4
  • k

    Klitos Kyriacou

    04/14/2022, 8:38 AM
    I've got an error message that I don't understand:
    val sqlServerDataSource = SQLServerDataSource()
            sqlServerDataSource.url = myUrl
            sqlServerDataSource.user = myUser
            sqlServerDataSource.password = myPassword
    The error is:
    Cannot access 'password': it is public/*package*/ for synthetic extension in '<library Maven: com.microsoft.sqlserver:mssql-jdbc:10.2.0.jre17>'
    There is no error on url or user; only on password. If I replace it with
    sqlServerDataSource.setPassword(myPassword)
    it works. But why can't I use the property syntax, and what exactly does the error message mean, and why only password has this error?
    m
    v
    e
    • 4
    • 6
  • a

    Alexander Maryanovsky

    04/14/2022, 12:43 PM
    Is there anything in Kotlin that would help with formatting a number with a given amount of significant digits (not decimal places)?
    e
    • 2
    • 2
  • r

    Ruckus

    04/14/2022, 6:04 PM
    I believe I found another bug with context receivers, but before I submit a new bug report, I'd like to do a quick sanity check here to make sure I'm not just making a dumb mistake. Code in thread.
    👀 1
    y
    • 2
    • 10
  • d

    dp

    04/14/2022, 6:17 PM
    Hi all! Just started learning Kotlin, enjoying it so far! 🙂 I’ve only done some coding via the Kotlin playground but I had a couple of questions. 1. When you have a lamda assigned to a variable, is there a way to get the compiler to say the “name” (the variable name) of a lamda function when errors occur? Right now, I get the below:
    // This code
    val add: (Int, Int) -> Int = { x, y -> x + y }
    
    fun main() {
        add(1, 2, 3)
    }
    
    // Gives me
    Too many arguments for public abstract operator fun invoke(p1: List<Int>): List<Int> defined in kotlin.Function1
    Versus with a named function
    //This code
    fun add (x: Int, y: Int): Int = x + y
    
    fun main() {
        add(1, 2, 3)
    }
    
    // Gives me
    
    Too many arguments for public fun add(x: Int, y: Int): Int defined in root package in file File.kt
    Side note: I don’t know why the former error message has this type annotation for the function (it doesn’t match what my code specifies):
    fun invoke(p1: List<Int>): List<Int>
    2. Is there a way to type a named function via extracting the types, like you can do with variables + lamda/anonymous functions?
    // Lamda with inline type annotations
    val add1 = { x: Int, y: Int -> x + y}
    
    // Lamda with extracted type annotations
    val add2: (Int, Int) -> Int = { x, y -> x + y}
    
    
    // Named function with inline type annotations
    fun add3 (x: Int, y: Int): Int = x + y
    
    // Named function with extracted type annotations
    ?
    This would be helpful so we could easily share type annotations among functions via a typealias. In addition this is particularly helpful for me because I find it harder to parse type annotations when they’re inlined. And I often like to be able to glance at function types and see if it matches what I need versus having to pick it apart from parameters. Thanks!
    j
    g
    • 3
    • 8
  • a

    Anthony Flores

    04/14/2022, 6:56 PM
    Is it possible to have inheritable / abstract inlined functions?
    d
    • 2
    • 1
  • a

    allan.conda

    04/15/2022, 10:04 AM
    Anyone know why this doesn’t work
    val nullableFoo: Any? = null
    val nonNullFoo = nullableFoo != null
    if (nonNullFoo) {
       acceptsNonNullFoo(nullableFoo) // expected Any but is Any?
    }
    but this works
    val nullableFoo: Any? = null
    if (nullableFoo != null) {
       acceptsNonNullFoo(nullableFoo)
    }
    🤔
    j
    v
    +2
    • 5
    • 6
  • r

    Ruckus

    04/15/2022, 3:26 PM
    Is there a way to call a non-context function from within a context function of the same name?
    fun generate(selection: Selection, values: Values) { ... }
    context(Scope) fun generate(selection: Selection, values: Values) =
        generate(this@Scope.selection refine selection, values)
           ^ this is a recursive call, but I would like to call the other (non context(Scope)) generate function
    y
    • 2
    • 4
  • t

    Tianyu Zhu

    04/15/2022, 9:47 PM
    I would like to write something like this:
    fun test(foo: List<Number>) {
      if (foo.containsOnly<Int>()) {
        val bar: List<Int> = foo
      }
    }
    Note that I don't want to use
    filterIsInstance()
    here. Is it possible to write an extension function that allows for this smart-cast?
    m
    • 2
    • 2
  • s

    smit01

    04/16/2022, 9:04 AM
    interface Logger {
       fun log(value:String)
    }
    context(Logger)
    open class A
    
    class B(): A()
    Do i need a Logger context to create a object of class B?
    g
    • 2
    • 1
  • l

    LastExceed

    04/16/2022, 9:59 AM
    why can i do
    val x: List<Int> = listOf(1, 2, 3)
    val y: List<Number> = x //works fine
    but not
    val x: Array<Int> = arrayOf(1, 2, 3)
    val y: Array<Number> = x //error: type mismatch
    ?
    r
    • 2
    • 6
  • g

    Gabor Torok

    04/16/2022, 5:53 PM
    Hi, this might be a bit unconventional question, but right now i am working on a presentation that should convince leadership that it’s okay for us to use Kotlin. so far the presentation is mostly about addressing/mitigating the risks/concerns involved, but of course I also have to convince people that it is worth taking on those risks. this creates an interesting problem. for me Kotlin does have a huge list of benefits, but due to the time constraints and attention span constraints i can’t really just go ahead and nerd out about them. also the audience is a bit different, have to aim at leadership instead of the developer. so the question is: if you have 3 slides to talk about why how using Kotlin would benefit your manager, which features/benefits would you talk about and why?
    d
    a
    +2
    • 5
    • 9
  • k

    Kevin

    04/19/2022, 9:13 AM
    Hi, right now i'm trying to build a Design System/UI Package in Kotlin, and i didn't have too much experience of developing in Kotlin, so currently i would like to know if anyone has any resources where i can learn to build one. i have tried to search in many places but haven't found any resources that really match what i wanted to build. here i'll share the

    link▾

    of what i wanted to achieve, the Design System in the link was build in Flutter, but it only serves as reference so that you understand what i would like to achieve while developing the Design System in Kotlin(skip to 2:54). i'm sorry before if i referencing other programming language, but this is the only reference of Design System development that i could find.
    k
    • 2
    • 3
  • l

    Landry Norris

    04/19/2022, 3:25 PM
    Is there an idiomatic way to write a while loop that checks some boolean condition, but also stops after some maximum number of loops? I have a loop that runs very often, but under rare conditions, it will run infinitely. In this case, I’m supposed to break from the loop after some number of iterations (250 in this case), regardless of whether the task the loop is trying to complete is completed. Right now, I’m creating a variable called i and incrementing it every iteration and adding i < 250 to the loop condition.
    c
    y
    +2
    • 5
    • 10
Powered by Linen
Title
l

Landry Norris

04/19/2022, 3:25 PM
Is there an idiomatic way to write a while loop that checks some boolean condition, but also stops after some maximum number of loops? I have a loop that runs very often, but under rare conditions, it will run infinitely. In this case, I’m supposed to break from the loop after some number of iterations (250 in this case), regardless of whether the task the loop is trying to complete is completed. Right now, I’m creating a variable called i and incrementing it every iteration and adding i < 250 to the loop condition.
I figure it wouldn’t be too hard to make an extension function if this doesn’t exist, but I wonder if the stdlib has something like this.
c

Casey Brooks

04/19/2022, 3:51 PM
I don’t think there’s anything in the stdlib for running a loop like what you’re describing. I think that would lead to a pretty brittle code, not something that should be in the stdlib. If the loop is in a coroutine, then withTimeout might be a better way to handle this kind of use-case
l

Landry Norris

04/19/2022, 3:59 PM
Are there any performance implications of a coroutine using withTimeout? One place where I use this is in a function that should not take more than 15ms (ideally 10ms). Using withTimeout may be preferable to counting iterations if there’s not too much overhead associated with it.
y

Youssef Shoaib [MOD]

04/19/2022, 4:22 PM
You could do something with non-local returns like so:
run containingScope@ {
    repeat(250){
        if(someCondition){
            return@outerScope Unit
        }
    }
}
l

Landry Norris

04/19/2022, 4:28 PM
I did something similar at one point. I think I refactored it since I wanted to make it more clear that someCondition was the primary condition and the loop counter was a secondary condition.
r

Ruckus

04/19/2022, 5:07 PM
var tries = 0
while (someCondition && tries++ < 250) {
    ...
}
is probably what you already tried, but it seems like the most straight forward solution to me. Not sure why you'd want some other construct for it, unless I'm missing some context.
l

Landry Norris

04/19/2022, 5:13 PM
That's what I did at the end. It's clear on primary and secondary conditions. I just wanted to check if there was a clean stdlib way of doing this that doesn't add an extra tries variable. If not, I'll just stick with the tries method.
r

rocketraman

04/20/2022, 5:00 AM
@Landry Norris You could use a sequence. Example:
generateSequence { task() }
  .takeWhile { someCondition }
  .take(250)
l

Landry Norris

04/20/2022, 4:47 PM
I didn't see that. I can see that being a good alternative. Thank you.
r

rocketraman

04/20/2022, 5:14 PM
Yes its actually quite nice and completely avoids the
var
. If the task is suspending, you use the same pattern with a flow builder e.g.
flow { emit(task()) }
.
View count: 2