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

    kevinherron

    03/05/2021, 2:43 AM
    anybody know if
    kotlin.Result
    becomes usable as a return value in 1.5?
    i
    p
    • 3
    • 2
  • k

    knthmn

    03/05/2021, 4:43 AM
    In kotlinx.coroutines, there are functions like
    atomic<T>()
    but Intellij cannot resolve it. What are those and where are they defined?
    e
    • 2
    • 1
  • w

    Will Mwendwa

    03/05/2021, 7:41 AM
    Anyone who knows any opensource pure kotlin repos. Please no kotlin android
    b
    o
    +2
    • 5
    • 5
  • p

    Priyank Jain

    03/05/2021, 8:40 AM
    Hello, How can I compare generic class with list class? I have a generic class named BaseResponse now I want to extract the actual type "O" from the base-response. I have used the inline function with reified type parameter as defined in kotlin documentation but it is not working. This is my function in which I am passing the base response model and comparing the java class and getting the actual object. But If there is a List type like BaseResponseModel<List> it is always going in the else branch, not in the first comparison of the when statement.
    inline fun <reified O> getAPIResult(apiResponse: BaseResponseModel<O>): O? {
        val actualResult: O? = try {
            when (O::class.java) {
                List::class.java -> {
                    apiResponse.getResponseModel(object : TypeToken<List<O>>() {}.type)
                }
                ArrayList::class.java -> {
                    apiResponse.getResponseModel(object : TypeToken<ArrayList<O>>() {}.type)
                }
                else -> {
                    apiResponse.getResponseModel(O::class.java)
                }
            }
        } catch (e: Exception) {
            null
        }
        return actualResult
    }
    m
    • 2
    • 3
  • g

    Gopal S Akshintala

    03/05/2021, 10:25 AM
    How can I use Kotlin Function type as a Data type within Java? For example: I have a typealias 
    typealias _Validator_<_ValidatableT_, _FailureT_> = _suspend_ (_ValidatableT_) -> _Either_<_FailureT_, Any?>
    Within Kotlin, I use it like this as a data type to assign to a lamda 
    val validateParent3X: _Validator_<_Egg_, _ValidationFailure_> = {...}
    But I cannot use typealias from Java. What is the idiomatic way to use this Function type as data type on Java? I see two unknows I have for java interoperability. 1. How can I idimotically refer a Function type 2. Function type being 
    suspend
    v
    a
    • 3
    • 2
  • a

    Andrew

    03/05/2021, 10:26 AM
    Is it possible to add annotations to extension functions? I am currently writing an extension function that returns a string based on the value of an Int:
    fun Int.toFriendlyName(): String{
        return when(this) {
            PredefinedValue1 -> "PredefinedValue1"
            PredefinedValue2 -> "PredefinedValue2"
            PredefinedValue3 -> "PredefinedValue3"
            else -> willNeverHappen("This value is not supported")
        }
    }
    However this is problematic as this extension function can now be used on all integers in the scope of the extension functions. I know that the `Int`s that I will be calling this on will be annotated with @Barcode.BarcodeFormat - so is there a way for me to mark that on my extension function so that I can only use it on integers with that specific annotation?
    r
    j
    a
    • 4
    • 11
  • j

    jeggy

    03/05/2021, 10:47 AM
    I haven't fully understood how SAM works. But would it be possible to mix it with enum classes? so instead of having something like this:
    fun interface Ordering {
        fun String.getOrdering(): List<String>
    }
    
    enum class CustomValueCriteriaOrder : Ordering {
        ALPHABETICALLY {
            override fun String.getOrdering(): List<String> {
                return emptyList()
            }
        }
    }
    I could have
    fun interface Ordering {
        fun String.getOrdering(): List<String>
    }
    
    enum class CustomValueCriteriaOrder : Ordering {
        ALPHABETICALLY { emptyList() }
    }
    d
    a
    • 3
    • 12
  • n

    nglauber

    03/05/2021, 2:40 PM
    Is there a workaround for this issue? https://youtrack.jetbrains.com/issue/KT-34051
    y
    • 2
    • 8
  • y

    Yan Pujante

    03/05/2021, 5:49 PM
    I am using the
    kotlin.time.Duration
    concept in my code and see that I can convert to
    String
    pretty easily. I am not seeing a way to go the other way around, which makes it quite hard to use it as a field in a form or to save/retrieve in preferences... Am I missing something?
    y
    i
    • 3
    • 7
  • s

    Santosh Astagi

    03/05/2021, 7:07 PM
    I am trying to investigate value classes, but in intellij, when I try to add @JvmInline, it is unable to find it
    y
    • 2
    • 3
  • k

    Kush Patel

    03/06/2021, 1:13 AM
    👋🏽 I’m trying to understand if there is a difference between the following blocks of code. Personally, I find that B is easier to read and understand in a sense that I don’t need to know what exactly
    apply {}
    does in order to understand the code. I am more curious to understand if there is some sort of tradeoff I’m missing here if one chooses A over B or vice versa. Thanks!
    // A
    val setOfInts = HashSet<Int>().apply{
        for (i in 0..20) {
            this += i
        }
    }
    
    // B
    val setOfInts = mutableSetOf<Int>()
    for (i in 0..20) {
        setOfInts.add(i)
    }
    z
    e
    +2
    • 5
    • 11
  • y

    Youssef Shoaib [MOD]

    03/06/2021, 12:04 PM
    Quick question because I can't find this anywhere online. So most Apache 2.0 licensed work uses the long-form, boilerplate notice at the top of each file, and in that case if you're making a derivative of it you just add another "Copyright YYYY Firstname Lastname" line underneath the already existing one, but the Kotlin compiler code uses this shorthand form:
    /*
     * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors.
     * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
     */
    so in this case should I change it to " Copyright 2010-2019 JetBrains s.r.o., Kotlin Programming Language contributors, and Firstname Lastname", or what should I do?
    :thread-please: 2
    v
    • 2
    • 4
  • s

    Slackbot

    03/06/2021, 8:49 PM
    This message was deleted.
    a
    s
    • 3
    • 2
  • t

    therealbluepandabear

    03/07/2021, 3:58 AM
    Is there a more concise way of doing the following:
    fun charToNumber(input: Char): Int {
        val numbersToLetters = listOf('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
        'T', 'U', 'V', 'W', 'X', 'Y', 'Z')
    
        return numbersToLetters.indexOf(input.toUpperCase()) + 1
    }
    e
    r
    i
    • 4
    • 7
  • t

    therealbluepandabear

    03/07/2021, 4:15 AM
    would this work:
    for (number in input.toString().split("")) {
        
    }
    r
    e
    • 3
    • 3
  • u

    123

    03/07/2021, 12:16 PM
    Anything I can do to exclude a particular field from data class
    .toString()
    except overriding it? I have a LAZY collection in a data class, so it throws an exception on
    .toString()
    a
    n
    • 3
    • 2
  • g

    Grigorii Yurkov

    03/07/2021, 4:34 PM
    What is the lowest common ancestor of
    Array<Int>
    and
    Array<in Int>
    ? In my opinion it should be
    Array<in Int>
    . But kotlin compiler thinks it's
    Array<out Int?>
    . I agree that
    Array<out Int?>
    is supertype of both
    Array<Int>
    and
    Array<in Int>
    , but it's not the lowest. What do you think?
    i
    • 2
    • 1
  • t

    therealbluepandabear

    03/08/2021, 4:24 AM
    I was never good at probability at school
    e
    v
    y
    • 4
    • 5
  • v

    vineethraj49

    03/08/2021, 4:45 AM
    something something shakespeare with monkeys on a typewriter
    t
    • 2
    • 3
  • t

    therealbluepandabear

    03/08/2021, 7:33 AM
    Seems as though I reached the limit of Int... Should've used 'double' for numbering. Anyways, passed almost 3 hours; hasn't found 'TOMJONEYWASHERE'. I will try again tomorrow:
    u
    y
    k
    • 4
    • 3
  • k

    kqr

    03/08/2021, 8:21 AM
    @therealbluepandabear please stop spamming, use threads
    ➕ 13
    ☝️ 7
    👍 25
    k
    • 2
    • 2
  • r

    Rob Elliot

    03/08/2021, 8:41 PM
    Is there an out of the box way to take from an Iterable until a predicate is satisfied, including the element that first satisfies the predicate? Something like:
    val xs = listOf("a", "e", "c", "b", "d")
    xs.takeUntil { it == "c" } == listOf("a", "e", "c")
    s
    n
    +2
    • 5
    • 8
  • t

    TwoClocks

    03/08/2021, 10:26 PM
    why doesn't this compile :
    val one = """text \$text"""
    it won't escape the $. Works fine in a normal string. how do I turn of templating in raw strings?
    z
    r
    +3
    • 6
    • 21
  • t

    therealbluepandabear

    03/09/2021, 12:22 AM
    In a compute program, how would I calculate in Kotlin where the values of a list are all equal to each to each other? Thank you.
    e
    e
    n
    • 4
    • 23
  • t

    therealbluepandabear

    03/09/2021, 1:21 AM
    I have a weird question... Given a while(True) loop, how can I make it run faster? Are there any ways or does this just depend on the amount of code taht's executed each time?
    c
    • 2
    • 1
  • j

    Jack Darlington

    03/09/2021, 10:55 AM
    I have got a question on Kotlin serialization. I want to use sealed classes to deserialize. Is there a way to change the type key from "type" to something else on the sealed class.
    p
    • 2
    • 2
  • a

    Aness Iqbal

    03/09/2021, 11:05 AM
    Help! I have lost the release key which I used to sign apk builds in Android Studio. Can I get/extract that release Key info from apk? I have already tried to make a new key with almost the same info but the time/validity info is unable to match. And now I am unable to install the update on the apk already installed version on mobile.
    🇳🇴 2
    :google: 2
    :stackoverflow: 4
    c
    • 2
    • 1
  • r

    Rob Elliot

    03/09/2021, 11:37 AM
    Just found I’ve made a completely invalid assumption about
    singleOrNull
    - I assumed it would throw an exception if size > 1, but it returns null.
    t
    r
    y
    • 4
    • 8
  • o

    Olivier Patry

    03/09/2021, 2:23 PM
    Hi 👋, maybe a silly question related to Java/Kotlin interop, I face something that worries me 😱 In Java, a legacy class exposes
    public void setFoo(@NonNull Bar bar)
    {
      // ...
    }
    In Kotlin side
    myObject.foo = null // OK
    myObject.setFoo(null) // KO
    The property access compiles 😱 The function call doesn't compile 👍 Is it expected? Can I avoid exposing
    setFoo
    as a Kotlin property at will? It seems fragile to allow such property access, no?
    👀 4
    😱 2
    r
    • 2
    • 7
  • d

    droid

    03/09/2021, 3:17 PM
    Is there a guide to understanding time, space complexity for kotlin utility functions? e.g. “str”.reversed(), arr.sortedBy{ } etc.
    n
    n
    +2
    • 5
    • 12
Powered by Linen
Title
d

droid

03/09/2021, 3:17 PM
Is there a guide to understanding time, space complexity for kotlin utility functions? e.g. “str”.reversed(), arr.sortedBy{ } etc.
n

nanodeath

03/09/2021, 5:59 PM
no but the source is usually very readable. only problem with that is the source can change; it's not a part of the documented contract.
n

Nir

03/09/2021, 7:28 PM
It is somewhat surprising that it's not part of the spec, IMHO
Sorts for example should guarantee worst case N log N, developers shouldn't have to guess or read source. Maybe they are constrained because they want to use JVM implementations on that platform, and they don't make that guarantee, officially
g

groostav

03/10/2021, 12:00 AM
kotlin wants to give you what the platform already has, and remember for native/js that may be different than JVM. Those methods are there for convenience, and are in most cases pretty fast, but they're also very functionally oriented, meaning you're going to blow up your runtime performance with memory thrashing anyways
ahem, bump for kotlinx immutable collections: https://github.com/Kotlin/kotlinx.collections.immutable
n

Nir

03/10/2021, 12:30 AM
There are in place sorts
and no guarantees are given in that case either
So, eh, I dunno about that idea, it amounts to saying its slow anyway, so who cares
But if the array is large, N log N with bad constants is probably still bearable, but N^2 probably is just not ok even with good constants
d

droid

03/10/2021, 1:12 AM
Thank you guys for the response.
With the utility functions making things simpler, figuring out complexity right off seems confusing.
a

Alexey Belkov [JB]

03/10/2021, 12:41 PM
Related issue: https://youtrack.jetbrains.com/issue/KT-25425
➕ 2
View count: 6