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

    dMusicb

    05/04/2022, 7:19 PM
    Haven't used Kotlin serialization much, what's the correct way to be able to deserialize some JSON returned by an API when it's something like:
    {
        "type": "Foo" | "Bar" | "Baz"
        "payload": FooPayload | BarPayload | BazPayload
    }
    l
    p
    • 3
    • 11
  • m

    martmists

    05/04/2022, 11:33 PM
    When working with delegates, how should I handle situations like this?
    class MonoNode : BaseNode() {
        protected val input by input()    // getValue should resolve here; it's a delegate to use the property name
        protected val output by output()  // getValue should not resolve as its value may change over time
    
        override fun process() {
            // We don't want to call getValue too often in real-time code that needs to be fast!
            // output.getValue should only be called once per process() call
            // input.getValue should only be called in constructor/init
            // Is there a good way to do it without having to store to a variable?
    
            val x = input[0]   // calls input.getValue
            val y = input[1]   // calls input.getValue
            output[0] = x + y  // calls output.getValue
            output[0] = x + y  // calls output.getValue
        }
    }
    🇳🇴 1
    c
    • 2
    • 1
  • a

    ahmad

    05/05/2022, 9:47 AM
    Hi all, I have a list of strings and I need to batch it into list of list where each list doesn’t exceed 10 items AND also each list doesn’t exceed 100 chars. for example
    input: [ "this is item number one",
             "this is item number two",
             "this is item number three",
             "this is item number four",
             "this is item number five",
             "this is item number six"
           ]
    
    output: [
             ["this is item number one", "this is item number two", "this is item number three", "this is item number four"],
             ["this is item number five", "this is item number six"]
           ]
    I wrote this
    private fun List<String>.batch(): List<List<String>> {
        return fold(mutableListOf(mutableListOf<String>())) { accumulator, string ->
            val currentBucket = accumulator.last()
            val currentBucketCharsCount = currentBucket.sumOf { item -> item.length }
            val willBucketExceedMaximumCharCount = currentBucketCharsCount + string.length > 100
            val willBucketExceedMaximumSize = currentBucket.size + 1 > 10
            if (willBucketExceedMaximumCharCount || willBucketExceedMaximumSize) {
                accumulator.add(mutableListOf(string))
            } else {
                currentBucket.add(string)
            }
            accumulator
        }
    }
    but I have a feeling that it can be done in a more cleaner/simple way. any ideas?
    r
    m
    r
    • 4
    • 6
  • i

    Ink

    05/05/2022, 4:21 PM
    Hi guys! I have string like that:
    [5-XR6Bwlq, 2-Hada32U1D, 7-aaGE7Ve84]
    I want to get every single number before
    -
    and create list of Int with that values. How I can achive that?
    k
    n
    • 3
    • 7
  • n

    nkiesel

    05/05/2022, 5:24 PM
    (I know it's more a Jackson than a Kotlin question, but I hope someone might have an answer anyway). I have a line `val jackson: YAMLMapper = YAMLMapper.builder().addModule(KotlinModule()).build()`in my code to create a Jackson YAML mapper with Kotlin extensions. This tells me "Kotlin: 'constructor KotlinModule(Int = ..., Boolean = ..., Boolean = ..., Boolean = ..., SingletonSupport = ..., Boolean = ...)' is deprecated. Use KotlinModule.Builder instead of named constructor parameters". Does that really mean I should use `val jackson: YAMLMapper = YAMLMapper.builder().addModule(KotlinModule.Builder().build()).build()`instead? That's an awful amount of build...
    e
    m
    • 3
    • 7
  • u

    ursus

    05/06/2022, 10:27 AM
    how can I merge these “duplicates”? its very unreadable for me // Also, why are the fields not in the source order? its not even alphabetical, I dont get it
    k
    • 2
    • 3
  • o

    Okan Yıldırım

    05/06/2022, 8:36 PM
    Hey, is there anything like partial classes in Kotlin? Lets say that I have a Post model with (id, title, content, createdAt, updatedAt) and I want to have only the primary fields (title, content) for the DTO Which way would be the most efficient to handle that in Spring Boot with Kotin
    r
    p
    • 3
    • 11
  • i

    Ink

    05/06/2022, 8:45 PM
    data class Foo(val price: Int?)
    val items = List<Foo>(Foo(133), Foo(324), Foo(3))
    How I can get
    List<Int?>
    with all prices? Is it only solution? https://medium.com/@hayi/kotlin-get-list-of-some-property-values-of-object-from-list-of-object-8da9419c2e77
    d
    c
    p
    • 4
    • 4
  • h

    Hassaan

    05/07/2022, 3:44 AM
    In kotlin : val a = 10 val b = 10 And in java : int x = 10 int y = 10 What’s the difference?
    e
    • 2
    • 8
  • h

    Hassaan

    05/07/2022, 3:57 AM
    correct me if i am wrong, in example above: in kotlin, both a and b refers to same value in memory while in java, both x and y are different values in memory
    :thread-please: 1
    k
    • 2
    • 2
  • a

    Andrew

    05/08/2022, 7:44 PM
    Is it possible to do something like this? fun foo(bar: (Int) -> String, block: () -> Unit) { // Some code } fun test() { foo { bar(5) // This is currently not valid but I need it to be } }
    p
    • 2
    • 10
  • s

    smit01

    05/09/2022, 2:06 PM
    Easy ways to get similar in kotlin In java int[] array = new int[6]; int[][] darray = new int[2][2]; And also how to get jagged array in kotlin?
    m
    • 2
    • 1
  • v

    Vampire

    05/09/2022, 6:10 PM
    Can I formulate
    fun Provider<out Task>.generateChecksums(destination: Directory? = null) {
        get().generateChecksums(destination)
    }
    
    fun Task.generateChecksums(destination: Directory? = null) {
    }
    
    fun FileSystemLocation.generateChecksums(destination: Directory? = null) {
    }
    somehow so that the first one can work for both
    Task
    or
    FileSystemLocation
    ? Just adding another method does not work of course as both would have the same type-erased form unless I call it differently.
    n
    e
    • 3
    • 11
  • s

    Stefan Oltmann

    05/10/2022, 10:32 AM
    Bitshifting for bytes is not supported in Kotlin and I try to figure out how I can translate this method into Kotlin code:
    /**
     * Returns an unsigned 16-bit int calculated from the next two bytes of the sequence.
     *
     * @return the 16 bit int value, between 0x0000 and 0xFFFF
     */
    public int getUInt16() {
            return (getByte() << 8 & 0xFF00) |
                   (getByte()      & 0xFF);
    }
    If I add
    .toInt()
    I can use the
    shl
    function, but the result is wrong. Is there already a standard function for this calculation?
    ✅ 1
    k
    m
    +2
    • 5
    • 8
  • d

    David Smith

    05/10/2022, 2:32 PM
    Does anyone know of a static analysis tool that I can use to check that a package and it’s children don’t contain any classes that do not have the
    internal
    modifier?
    r
    • 2
    • 3
  • v

    Vitali Plagov

    05/10/2022, 7:12 PM
    "abc".split("")
    splits into a list of Strings
    [, a, b, c, ]
    (5 elements) with an empty string at the beginning and end. Why is it so? And how to split the string into individual letters to the List<String>?
    v
    e
    +3
    • 6
    • 15
  • h

    hooliooo

    05/11/2022, 10:35 AM
    Is there Big O notation documentation on collection functions like https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/partition.html ? I found it pretty nice in the Apple documentation that they mention the complexity of the function https://developer.apple.com/documentation/swift/array/3017524-partition
    e
    • 2
    • 3
  • s

    Slackbot

    05/11/2022, 7:06 PM
    This message was deleted.
    :nospam: 16
    :not-kotlin: 11
    ✅ 1
    a
    • 2
    • 2
  • d

    David Smith

    05/13/2022, 10:22 AM
    I’m trying to get kapt working on a multiplatform gradle project, so far I have:
    configure<org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension> {
        jvm {
            val main by compilations.getting {
                kotlinOptions {
                    freeCompilerArgs = listOf("-Xallow-result-return-type", "-Xinline-classes")
                    jvmTarget = JavaVersion.VERSION_11.toString()
                    javaParameters = true
                }
            }
        }
        sourceSets {
            val main by getting {
                dependencies {
    ...
                    configurations["kapt"].dependencies.add(platform("io.micronaut:micronaut-bom:${properties["micronautVersion"]}"))
                    configurations["kapt"].dependencies.add(project.dependencies.create("io.micronaut:micronaut-inject-java"))
                }
            }
        }
    }
    however when I run the
    kaptKotlinJvm
    task I’m getting:
    java.lang.IllegalArgumentException: The argument does not represent an annotation type: io.micronaut.context.annotation.Replaces
    Any idea what I’m missing? What does this error mean, that the dependencies aren’t working or something else?
    j
    • 2
    • 52
  • u

    ursus

    05/13/2022, 11:05 PM
    I have a api which takes varargs. Its basically a wrapper around String.format and there is a few layers to it. From what I see in the bytecode, every function call forces me to use spread operator which creates a copy of the vararg string array. Should I optimize this away and pass around only a Array<String>? feels very wasteful .. I mean we pass by reference on JVM // Not to mention if I call kotlin
    format
    then there is another damn copy when it proxies to java TLDR; are vararg apis harmful?
    e
    • 2
    • 4
  • m

    martmists

    05/15/2022, 11:44 PM
    Is something like the following possible somehow?
    class BaseType {
        val someProp: Int = 10
    }
    
    fun handleProperty(prop: KProperty1<BaseType, Int>) {
        // get BaseType instance here somehow
    }
    
    fun main() {
        val x = BaseType()
        handleProperty(x::someProp)
    }
    e
    • 2
    • 3
  • m

    Minsoo Cheong

    05/16/2022, 8:03 AM
    Hi, is there a known best practice for encoding/decoding kotlin objects to/from Base64 String instead of going object -> json string -> base64 and the opposite?
    j
    s
    • 3
    • 3
  • p

    Phani Mahesh

    05/17/2022, 7:43 AM
    not sure if there is a better channel but what is the advantage of definitely non nullable types?
    j
    r
    +4
    • 7
    • 23
  • f

    frogger

    05/17/2022, 11:02 AM
    we want to check permissions / scopes in our code. The scope names are defined externally, e.g.
    spreadsheets:read.all
    We would use is e.g. as
    requireScope("spreadsheets:read.all")
    I like plain text here over using constants like
    SPREADSHEETS_READ_ALL
    because it stays in the domain language of the scope, rather than using the kotlin constant. But it would be great to have some sort of compile time check here so you cannot have a typo in the scope string. (They are all known ahead). Any ideas?
    j
    m
    • 3
    • 8
  • l

    Lawrence

    05/17/2022, 7:06 PM
    Hello, I am migrating my Java modules + Gradle modules application to Kotlin. In one of my modules, I am getting all the packages in another module by
    ModuleLayer.boot().findModule(moduleName)
    . Now when I moved that code over to Kotlin, I noticed that particular module is not included in the ModuleLayer. I understand that Kotlin doesn't have an equivalent of
    module-info.java
    (I think) so does that mean this way of loading packages not gonna work in Kotlin?
    ✅ 1
    v
    e
    • 3
    • 3
  • n

    nkiesel

    05/18/2022, 4:32 AM
    I want to model a multi-dimensional hierarchy of status codes: I have different operations like "generate data" or "upload file", and for each of them I have either "success" or "failure". All "failure" should carry a message, and groups like "generate" or "upload" also share some attributes. The existing code uses an enum for the different status codes and then a bunch of nullable properties for the different properties (nullable because they are sparsely filled/used). A better way seems to be a sealed class hierarchy. But modelling this straight forward would require multi-inheritance. Is there a good way to model this?
    sealed interface Status
    sealed class Failure(val message: String) : Status
    sealed class Upload(val name: String) : Status
    sealed class UploadFailure(message: String, name: String) : Failure(message), Upload(name)
    c
    s
    • 3
    • 4
  • d

    David Smith

    05/18/2022, 10:13 AM
    I’ve written a custom ktlint rule but when I try to run it with gradle using the ktlint plugin I get the following
    Too many element types registered. Out of (short) range. Most of element types (14991) were registered for 'Language: kotlin'
    I’m completely stuck on this, it works fine if I run the ktlint binary with the jar file directly, seems like its something to do with the gradle plugin?
    c
    • 2
    • 3
  • h

    hfhbd

    05/19/2022, 4:13 PM
    When should you use a computed getter and when a field inside an object returning another const/object? Real world use case:
    public object GlobalScope : CoroutineScope {
        override val coroutineContext: CoroutineContext
            get() = EmptyCoroutineContext
    }
    Why is coroutineContext not a field?
    override val coroutineContext = EmptyCoroutineContext
    j
    c
    d
    • 4
    • 6
  • e

    Endre Deak

    05/19/2022, 11:00 PM
    Not sure where does this question belong to, but I’m looking for some simple alternatives to
    Poet
    where I have full control on the generated Kotlin source code including removing redundant qualifiers, etc. My google research did not lead me any further than just construct the source as a String and write it to a file.
    c
    m
    • 3
    • 4
  • t

    Tariyel Islami

    05/20/2022, 9:27 AM
    Hi guys, I am pulling data from firestore. When I need to sort these data by name or id numbers, do I need to pull them again from firestore or should I sort my list? When I look at a few places on the internet, it pulls from the firestore. Which is the right approach?
    t
    a
    • 3
    • 7
Powered by Linen
Title
t

Tariyel Islami

05/20/2022, 9:27 AM
Hi guys, I am pulling data from firestore. When I need to sort these data by name or id numbers, do I need to pull them again from firestore or should I sort my list? When I look at a few places on the internet, it pulls from the firestore. Which is the right approach?
t

tseisel

05/20/2022, 11:25 AM
It's almost always better to request data from Firestore already sorted, especially if you are requesting a large collection or would like paginated results.
t

Tariyel Islami

05/20/2022, 1:30 PM
Hi @tseisel Thank you for answer, Yes, I can guess that, but why is it better to pull the data again in order instead of sorting the data that I have already pulled once?
t

tseisel

05/20/2022, 2:46 PM
If you already have fetched the unsorted data, it would be wasteful to request Firestore again just to sort the same data.
a

Advitiay Anand

05/22/2022, 1:47 PM
Why don't you just request the data once as sorted? The upside is that you don't have to waste the client device's resources doing any more processing on the fetched data.
t

Tariyel Islami

05/23/2022, 12:09 PM
@Advitiay Anand For example, in case he wants to sort by name, age, id number.
a

Advitiay Anand

05/23/2022, 12:37 PM
Right. It actually depends on how big the data is, and how costly it is to sort it. If you're building a small project then it does not matter. Just sort it on the device. However, if the data is quite large, then you should keep it sorted / filtered on the backend, and simply make paginated requests. Try to save the user from any possible lags.
t

Tariyel Islami

05/23/2022, 4:47 PM
I thought it was like that too Many tutorials on the Internet were pulled directly from the database. That’s why I wanted to confirm my opinion. Thanks for your answers.
👍 1
View count: 8