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

    Karlo Lozovina

    02/25/2022, 7:33 PM
    Is there a way to call EnumSet.noneOf() given only a generic type parameter, let's say T? Neither
    noneOf(T::class.java)
    ,
    noneOf(T::class)
    work. If I pass around a value, then everything works fine (
    noneOf(value::class.java)
    ), but is there a way to keep everything on the type level?
    r
    p
    • 3
    • 7
  • a

    Advitiay Anand

    02/25/2022, 10:58 PM
    What's the easiest way to use Kotlin / JS for static front-end applications? Compose or any other framework ? I'm only just familiar with JS' syntax but have almost nil web experience :)
    r
    h
    • 3
    • 3
  • y

    Yatin Shelke

    02/27/2022, 12:10 AM
    Hi, i am new to kotlin multiplatform. Started with this sample Build a Full Stack Web App with Kotlin Multiplatform, and was able to get it running. However, when i tried to generate a test for the get method in the example in Server.kt, i see that the imports in the generated test do not get resolved. What dependencies do i need to add to build.gradle.kts to get this working? Would be nice to write tests along with the code. See screenshot that shows imports in red.
    a
    a
    • 3
    • 3
  • s

    Sean Proctor

    02/27/2022, 10:23 AM
    Is there a more concise way to write this:
    val result = foo.method1()
        .let {
            if (condition) {
                it.method2()
            } else {
                it
            }
        }.method3()
    a
    k
    +2
    • 5
    • 9
  • k

    Klitos Kyriacou

    02/28/2022, 3:11 PM
    Today I learned:
    fun foo(args: IntArray) {
        val a = intArrayOf(*args)  // Creates a copy of args
        //val b = intArrayOf(args)  // Compile error
        val c = intArrayOf(elements = args)
    }
    To pass an array to a varargs parameter, we are supposed to use the spread operator
    *
    . But that creates a copy of the array, which you might not want to do if you are calling a pure function in a loop. You can't pass the array itself, but I learned that you can pass it if you use a named parameter! Where in the documentation does it say that? [Update: looking at the generated bytecode, the call
    intArrayOf(elements = args)
    also copies the array, and produces the same bytecode as using the spread operator.]
    😲 2
    y
    • 2
    • 2
  • m

    Mark

    03/01/2022, 2:30 AM
    Which is the most appropriate way to convert:
    val foos: List<Foo> = ...
    foos.takeIf { it.isNotEmpty() }
    to a function reference 1️⃣
    foos.takeIf(List<Foo>::isNotEmpty)
    2️⃣
    foos.takeIf(List<*>::isNotEmpty)
    3️⃣
    foos.takeIf(Collection<Foo>::isNotEmpty)
    4️⃣
    foos.takeIf(Collection<*>::isNotEmpty)
    5️⃣ leave it as a lambda
    3️⃣ 1
    5️⃣ 10
    4️⃣ 1
    1️⃣ 2
    g
    e
    +3
    • 6
    • 14
  • u

    毛小川

    03/01/2022, 9:08 AM
    Hello! Does
    .forEach{it->}
    guarantee the original sequence during execution?
    :yes: 2
    g
    v
    • 3
    • 11
  • a

    Anthony Flores

    03/01/2022, 4:49 PM
    Hey, is there some way to check if a lazy variable is initialized without using reflections?
    s
    j
    y
    • 4
    • 17
  • t

    Timo Stark

    03/01/2022, 7:25 PM
    Hi Folks - I have a question and I am not sure whats the best palce to ask. I am working with Mockito tests and Kotlin and can't make my
    given
    stub working. Any Idea where to ask?
    r
    m
    m
    • 4
    • 4
  • a

    Anthony Flores

    03/01/2022, 7:57 PM
    Is it possible to accept a sequence of values and have a method that accepts them? Example:
    (255, 255, 255, 255)toRGBA()
    r
    v
    +4
    • 7
    • 17
  • t

    Turyin

    03/02/2022, 11:27 AM
    How do I join the fleet slack group?
    :not-kotlin: 1
    v
    • 2
    • 2
  • p

    Phani Mahesh

    03/02/2022, 12:13 PM
    Is there a way to restrict usage of external functions in a dsl? I’m thinking about creating and exposing a dsl using which users can provide their own domain spec. Is there a way to restrict them from using non whitelisted imports or language features?
    s
    • 2
    • 1
  • r

    Rob Elliot

    03/02/2022, 3:32 PM
    Is there a way in the stdlib to reduce a bunch of
    Result
    instances into a single Result? I can write it myself but a shame to repeat it. I want roughly the following:
    data class Foo(val a: String, val b: Int)
    
    val resultA: Result<String> = TODO()
    val resultB: Result<Int> = TODO()
    
    val foo: Result<Foo> = reduce(resultA, resultB, ::Foo)
    So the function would look something like:
    fun <A, B, T> reduce(a: Result<A>, b: Result<B>, work: (A, B) -> T): Result<T>
    But obviously it would need loads of overloads.
    j
    m
    a
    • 4
    • 8
  • m

    Michael Langford

    03/02/2022, 5:01 PM
    Conditional Compilation: I know if I have a large pile of isolated code, I can easily conditionally compile it via module. My context here is an a mobile device android app only. However, I want to remove a pervasively used function call throughout the app for release. Let's call it "PrintStuffWeMayNotWantPrintedIn Production(varargs:List<ValuableData>)". I don't want to inactivate it, but remove it. My app functions in a somewhat adversarial situation (a medical app, low risk, but does have pentesters and curious teens to work through). I wish to not leave these call sites throughout the app as a hook that is exploitable to easily gain a bunch of info with tools such as Frida. Would this plan work: Conditionally compile out the actual part that prints/logs via BuildConfig.DEBUG then use proguard to remove the actual statement calls too? Or do I need to inline the functions too? Or is there a more "kotlinesque" way to remove/elide all the PrintStuffWeMayNotWantPrinted() calls from the app using a feature I just can't find the name of? (I'd ask other places for Proguard tips re the above, but if there are kotlin specific caveats I should be reading about, I'm all over reading your feelings or specific reference doc on the topic or even years of developer forum debate. I just don't really see more than brief exchanges on this topic)
    ✅ 1
    y
    j
    • 3
    • 4
  • m

    Mason M

    03/02/2022, 9:19 PM
    Is it possible to catch exceptions if they are not of a certain type?
    r
    e
    • 3
    • 3
  • a

    Ayden

    03/05/2022, 3:27 AM
    Hello everyone. I encounter the error when using
    JDK 17
    and
    Gradle 7.3.3/7.4
    ,
    Unsupported class file major version 61
    . I think the solution to resolve this is to downgrade the JDK version to 11 after searching through the internet. What should I do to resolve this issue if I insist to use JDK 17. I am using WSL2, with the following setup for my console application.
    JDK: 17
    Build System: Gradle Groovy
    Target JVM version: 16
    v
    • 2
    • 2
  • d

    Daeyoung Kim

    03/05/2022, 7:50 AM
    I don’t know what was wrong. Anybody can explain this error?
    :thread-please: 2
    s
    a
    +2
    • 5
    • 8
  • c

    Chih Wei Lin

    03/05/2022, 5:10 PM
    How to solve the following problem more elegantly: Given a keyword list and a input data list. Iterate through input data list and if the item contains one of the keywords, put it together. (Sample data and my brute force way are in the thread)
    v
    r
    • 3
    • 5
  • a

    althaf

    03/08/2022, 12:08 PM
    hi
    when(args.approvalType) {
        ApprovalType.MULTI_SELECT_BATCH_APPROVAL.ordinal,
        ApprovalType.MULTI_SELECT_SINGLE_APPROVAL.ordinal -> {
            context?.apply {
                bgView.setBackgroundColor(getColor(R.color.sc_palette_green))
                subTitleTextView.text = getString(R.string.approvalSuccessLabelText)
            }
        }
        ApprovalType.MULTI_SELECT_SINGLE_APPROVAL.ordinal,
        ApprovalType.MULTI_SELECT_SINGLE_REJECT.ordinal -> {
            //TODO move to string resource
            titleLineTitleTextView.text = "List of Transactions"
        }
        ApprovalType.MULTI_SELECT_BATCH_APPROVAL.ordinal,
        ApprovalType.MULTI_SELECT_BATCH_REJECT.ordinal -> {
            //TODO move to string resource
            titleLineTitleTextView.text = "List of Batches"
        }
        ApprovalType.MULTI_SELECT_SINGLE_REJECT.ordinal,
        ApprovalType.MULTI_SELECT_BATCH_REJECT.ordinal -> {
            context?.apply {
                subTitleTextView.text = getString(R.string.rejectSuccessLabelText)
                bgView.setBackgroundColor(getColor(R.color.sc_palette_dark_blue))
            }
        }
    }
    Is this possible with when() to match two different blocks at the same time ? Here i need to match multiple blocks are the same time, in different context, to show the text "List of Transactions" and "List of Batches"
    m
    r
    r
    • 4
    • 7
  • l

    LastExceed

    03/08/2022, 7:29 PM
    is there a good way to associate something with a type in a way it can be generically looked up, but without each instance of the type holding a copy ? e.g. consider an abstract parent class
    Animal
    and some inheriting classes
    Dog
    Cat
    etc, and i want each type of animal to have a
    lifeExpectancy
    . now of course i could just create
    abstract val lifeExpectancy: Float
    inside
    Animal
    and have each child class override that, but that would result in every instance of
    Dog
    holding a copy of the same number, which seems a bit redundant. (yes i know the overhead in this example is insignificant, but the problem is scalable). alternatively i could put the lifeExpectancy in the companion object, but then i can't generically look it up as the companion object can't be accessed generically (or at least i wouldn't know how to do that). i could store a reference to the companion object (or just the data i want to associate with the type in case it's not a primitive) in each instance to keep the overhead insignificantly low, but that would be incredibly ugly is there any way to do this more elegantly?
    c
    t
    y
    • 4
    • 8
  • t

    Trevor Hackman

    03/08/2022, 10:06 PM
    Hi, I was interested in suggesting a new standard library function in kotlin.collections and in writing it myself and making a pull request to contribute, Is this something that would be of interest? I found myself wanting this function but it not existing in the standard library, it would be
    binarySearchIndexed
    With a signature of perhaps
    fun <T : Comparable<T>> List<T>.binarySearchIndexed(
        fromIndex: Int = 0,
        toIndex: Int = size,
        comparison: (T, Int) -> Int,
    ): Int
    d
    • 2
    • 2
  • a

    allan.conda

    03/09/2022, 1:29 AM
    Would it be bad practice to always override toString() to be the underlying value of an inline class? I'm not sure there's benefit to representing it as the boxed type by default. Asking because I recently made a mistake calling toString instead of the underk value
    j
    • 2
    • 2
  • m

    Marko Novakovic

    03/10/2022, 1:13 PM
    private fun UserContact?.isValid(): Boolean {
        contract {
            returns(true) implies (this@isValid != null)
        }
        return this != null &&
            userId.isNotBlank() &&
            !email.isNullOrBlank() &&
            !phoneNumber.isNullOrBlank()
    }
    suspend operator fun invoke(): UserData {
            val userData = getUserData()
            val contact = getUserContact()
            return when {
                contact.isValid() -> userData.fillInWithUserContact(contact)
                else -> userData
            }
        }
    compiler is complaining
    contact
    inside
    invoke
    fillWithUserContact
    is nullable. shouldn’t
    contract
    ensure it’s not treated as nullable?
    h
    j
    k
    • 4
    • 6
  • a

    Ayfri

    03/11/2022, 4:34 AM
    Is there a more efficient way than
    round(number / length) * length
    to round a number by a length ?
    m
    k
    t
    • 4
    • 10
  • n

    No_One

    03/11/2022, 10:40 AM
    Hi All, I am new to Kotlin (have a lot of java exp), what is the best way to get started to master kotlin ? I am okay to buy courses etc as I need to be up and running soon as my new project demands it. will be using it for building microservices with spring and Kafka etc.
    s
    j
    r
    • 4
    • 6
  • o

    oday

    03/11/2022, 2:00 PM
    how can i get back these variables to use them?
    "ticket-alert/remove/(?<id>.+)/(?<hash>.+)".toRegex()
    t
    n
    • 3
    • 12
  • n

    Nat Strangerweather

    03/11/2022, 6:27 PM
    Hi, hope this is the right place. I am trying to loop through a list of Strings so that I can create an array called Letter which is made of a String and an Int. The problem is that whatever I do, I only ever get the last value of my list of Strings. What could I be doing wrong?
    fun savedData(): Array<Letter> {
            val arr = mutableStateOf(boardLetters)
            if (savedValues != null) {
                for (item in savedLetters!!) {
                    arr.value = Array(28) {
                        Letter(item, 0)
                    }
                }
            }
            return arr.value
        }
    For info: boardLetters is this:
    boardLetters: Array<Letter>
    Thanks for any help.
    l
    n
    • 3
    • 11
  • a

    Andy Jiang

    03/11/2022, 11:51 PM
    Hi, I'm new to Kotlin and I have a question about the code snippet from the official doc:
    val a: Int = 100
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a
    val b: Int = 10000
    val boxedB: Int? = b
    val anotherBoxedB: Int? = b
    println(boxedA === anotherBoxedA) // true
    println(boxedB === anotherBoxedB) // false
    e
    • 2
    • 3
  • a

    Andy Jiang

    03/11/2022, 11:53 PM
    val a: Int = 100
        val boxedA: Int? = a
        val anotherBoxedA: Int? = a
        
        val b: Int = 10000
        val boxedB: Int? = b
        val anotherBoxedB: Int? = b
        
        println(boxedA === anotherBoxedA) // true
        println(boxedB === anotherBoxedB) // false
    :thread-please: 3
    t
    • 2
    • 3
  • j

    jcechace

    03/12/2022, 6:24 PM
    I have a library written in Kotlin which is then used as a dependency from Java code. Is it expected that KClass#primaryConstructor returns null?
    w
    • 2
    • 3
Powered by Linen
Title
j

jcechace

03/12/2022, 6:24 PM
I have a library written in Kotlin which is then used as a dependency from Java code. Is it expected that KClass#primaryConstructor returns null?
clazz.primaryConstructor!!.call(param)
When this line is executed from Kotlin code the primary consructor is returned. In Java I get a null value.
w

wrongwrong

03/12/2022, 7:03 PM
I don't know if I understand your question, but for example, the following will cause the
primaryConstructor
to be
null
even in a
Kotlin
class.
import kotlin.reflect.full.primaryConstructor

class C {
    val v: Int

    constructor(v: Short) { this.v = v.toInt() }
}

fun main() {
    println(C::class.primaryConstructor) // -> null
}
The
primaryConstructor
will never be
null
for a
data class
.
j

jcechace

03/13/2022, 3:48 PM
@wrongwrong I get that. In my case the class has primary constructor (its mandated by supertype). My issues is that with the ``primaryConstructor`` is when it’s accessed as part of Kotlin code base it’s there, when it’s from java it’s not… thinking about it… it makes perfect sense since Java classes probably don’t have a primary constructor :)… Thanks for being my rubber duck
View count: 3