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

    Mostafa Hadian

    03/12/2022, 11:35 PM
    Hi, I have a question about membership, is there any channel to use to ask the question or any member of admins can help me please?
    v
    • 2
    • 4
  • n

    No_One

    03/13/2022, 9:16 PM
    Does anyone use a website(s) to improve their coding? like hacker rank etc? I learn faster while trying to solve a problem than just reading about a new langauge.
    ✅ 1
    c
    r
    • 3
    • 4
  • g

    George

    03/14/2022, 10:14 AM
    Hi folks, Which is the proper way to enforce some piece of code to wait to be initialized something else first? I have something like this, but ofc it does not work.
    internal fun AtomicRef<MutableList<Pair<KClass<*>, KSerializer<*>>>>.getOrWait(): MutableList<Pair<KClass<*>, KSerializer<*>>> {
        while (this.value == emptyList<MutableList<Pair<KClass<*>, KSerializer<*>>>>())
            suspend {
                delay(10)
            }
        return this.value
    }
    Can anyone point any docs or articles on this subject? thanks in advance!
    j
    a
    n
    • 4
    • 8
  • l

    Lucas Schiavini

    03/14/2022, 12:40 PM
    Hi everyone! How you doing?
    👋 5
    v
    s
    t
    • 4
    • 3
  • s

    Samuel Ajibade

    03/14/2022, 10:12 PM
    And I was wondering if anyone knows about any good course material
    :thread-please: 5
    c
    • 2
    • 2
  • s

    S.

    03/14/2022, 10:16 PM
    google offers some kotlin courses specifically for android https://developer.android.com/kotlin
    ☝️ 1
    :thread-please: 1
    • 1
    • 1
  • o

    oday

    03/15/2022, 1:05 PM
    I have this map
    private val routes = mapOf<Regex, (vararg args: String) -> LaunchAction?>(
    I would like to accept a variable number of arguments in that anonymous function defined as the map’s value, how can I do that? I’m not allowed to set a modifier like
    vararg
    there
    y
    r
    • 3
    • 6
  • i

    Ido Flax

    03/16/2022, 6:46 AM
    I noticed that
    CoroutineScope.launch{ }
    takes 40 ms. Isn’t this a bit much? Part of the point of launching is that you don’t need to wait for it, but apparently you do need to wait 40 ms as least
    val scope = CoroutineScope(Dispatchers.Default)
        println(
            measureTimeMillis {
                scope.launch { }
            }
        )
    // 40
    This is done on a macbook pro 2021 m1 pro
    😲 1
    g
    j
    • 3
    • 9
  • v

    Vitali Plagov

    03/16/2022, 1:02 PM
    Hi. I have the following code
    val version = service.getAllTemplates()
      .find { ... }
      ?.versions // returns a list
      ?.single()
      ?: error("no template found matching the given predicate")
    I’m using the
    find{}
    on purpose so I could handle its failure with a proper error message, I want to do the same with
    single()
    . I want to throw an exception with my own error message if the list contains more than one element. I tried
    singleOrNull()
    but still can’t provide a separate error message for it. Looks like the last
    error(…)
    handles both nulls.
    m
    a
    e
    • 4
    • 7
  • n

    Nat Strangerweather

    03/16/2022, 4:30 PM
    Hi, Can anyone explain this please? I am expecting here to print a list of letters with the letter on which I clicked removed. Instead, what I get is "true".
    fun removeUsedLetters() {
            val boardLetters = readBoardLetters.value!!.toMutableList()
            val newList = boardLetters.remove(letter.value)
            println("remaining = $newList")
        }
    Why does
    remove()
    act as a Boolean, and how can I get each letter that I click on to be removed from my list?
    j
    e
    k
    • 4
    • 11
  • a

    Ayfri

    03/16/2022, 5:59 PM
    Hi, is it possible to add an external secondary constructor for a class ? I have a
    typealias AABB = Rectangle
    with an external "constructor"
    fun Rectangle(x: Int = 0, y: Int = 0, width: Int = 0, height = 0) = ...
    but it's not present on the type AABB, I also tested with
    fun Rectangle.invoke(x: Int ...
    but it still doesn't work, is it possible ?
    c
    r
    t
    • 4
    • 5
  • h

    Hozaifa Bhutta

    03/16/2022, 11:08 PM
    I know how to launch a new activity in native android. But I want to have a single shared function that launches a new activity in iOS and Android
    i
    s
    • 3
    • 6
  • a

    Anthony Flores

    03/17/2022, 1:34 AM
    Is it possible to have an operator function like
    val someProperty: SomeClass = 50%
    ?
    h
    p
    • 3
    • 3
  • k

    kierans777

    03/17/2022, 2:44 AM
    Hi. Does Kotlin support runtime polymorphism for functions?
    open class Animal(val name: String)
    class LandAnimal(name: String, val legs: Int) : Animal(name)
    class SeaAnimal(name: String, val flippers: Int) : Animal(name)
    
    fun printAppendages(animal: SeaAnimal) {
        print(" has ${animal.flippers} flippers")
    }
    
    fun printAppendages(animal: LandAnimal) {
        print(" has ${animal.legs} legs")
    }
    
    fun printAppendages(animal: Animal) {
        print(" has no appendages")
    }
    
    fun <T : Animal> printAnimal(animal: T) {
        print(animal.name)
        
        printAppendages(animal)
        
        print("\n")
    }
    
    fun main() {
        val lassie = LandAnimal("Lassie", 4)
        val nemo = SeaAnimal("Nemo", 2)
        
        printAnimal(lassie)
        printAnimal(nemo)
    }
    Lassie has no appendages
    Nemo has no appendages
    Or is polymorphic dispatch only for methods?
    j
    t
    • 3
    • 7
  • n

    Nat Strangerweather

    03/17/2022, 7:39 PM
    With this line of code, I have a situation where if there is one "A" in
    letterList.value
    all the "A"s in
    boardLetterList
    are removed. Is there a way of getting only one "A" filtered out if I only have one in my letterList?
    val difference = boardLetterList.filterNot{ letterList.value!!.contains(it) }
    y
    e
    • 3
    • 6
  • d

    David W

    03/17/2022, 10:37 PM
    I have a list of objects. Some are similar to each other and I'd like to merge those ones together. There's no object key - the similarity is fuzzy (I have the algorithm for comparing two objects already). Are there any list methods that would help me here? Or does it have to be done procedurally, rather than functionally? Maybe a better question is, can I create a grouping based on comparing objects, rather than by using a keyfinder? Sorry if wrong channel, I'll happily move to another one but wasn't sure where to ask.
    j
    e
    • 3
    • 11
  • j

    Jasin Colegrove

    03/18/2022, 3:03 PM
    Say I have a data class that accepts an item, that item could be one of say 4 different things. I know I can use the Any type but what's the best way to narrow the scope to those 4 items?
    👍 1
    s
    k
    s
    • 4
    • 3
  • j

    Jorge Bo

    03/18/2022, 7:50 PM
    Hi, is there any convention used in kotlin to decide where to place extension functions?
    t
    l
    • 3
    • 3
  • a

    Avi Perl

    03/18/2022, 8:54 PM
    I'm trying to choose what book to buy to learn Kotlin. I've found this page https://kotlinlang.org/docs/books.html but am a bit overwhelmed by all the good options. My background is Python, PHP, and JS, and I'm learning Kotlin to be able to use Vertx at work. I'm starting at 0, and would like to learn not just the syntax, but the Kotlin ways of doing things, the why's, and the ecosystem. Can anyone help me narrow down my choices with some recommendations?
    m
    s
    • 3
    • 2
  • t

    therealbluepandabear

    03/19/2022, 3:24 AM
    What does
    tailrec
    do here?
    tailrec fun Context.activity(): Activity? = when {
      this is Activity -> this
      else -> (this as? ContextWrapper)?.baseContext?.activity()
    }
    l
    e
    a
    • 4
    • 3
  • g

    Gavin Ray

    03/19/2022, 7:21 PM
    Would anyone be willing to explain to me what is happening in this image? I am having trouble understanding the type signature (never seen one like this before) and why it won't accept the value as a valid type
    and((MutableCollection<out Condition!>..Collection<Condition!>?))
    I think this means "A type with a lower-bounds of
    MutableCollection<out Condition!>
    and an upper-bounds of `Collection<Condition!>?`"
    But if that is true, then explicitly casting to either of those should have made it work, which it doesn't (as you see in the image) 🤔 😕
    c
    p
    • 3
    • 3
  • o

    oday

    03/20/2022, 10:08 PM
    this is an excerpt from https://developer.android.com/codelabs/kotlin-bootcamp-sams#1
    import kotlin.reflect.full.*
    
    class Plant{
        fun trim(){}
        fun fertilize(){}
    }
    
    fun testAnnotations(){
        val classObj = Plant::class
    
        for (m in classObj.declaredMemberFunctions){
            println(m.name)
        }
    }
    declaredMemberFunctions
    is still unrecognized
    j
    • 2
    • 4
  • r

    RE

    03/21/2022, 11:55 AM
    I'm wrapping a DoubleArray with the value class, but when the values of the same content compare, it return false
    s
    r
    k
    • 4
    • 7
  • j

    jcechace

    03/21/2022, 4:12 PM
    Hi, would anyone happen to know about workaround for https://youtrack.jetbrains.com/issue/KT-47703 ? Unfortunately there is a about dozen duplicates of this issue, however I haven’t managed to dig out the original https://youtrack.jetbrains.com/issue/KT-45395 does not mention it
    e
    a
    • 3
    • 3
  • h

    Hozaifa Bhutta

    03/21/2022, 10:09 PM
    I have an android app for my robotics team, how difficult would it be to migrate to kotlin multiplatform?
    t
    • 2
    • 1
  • j

    Jason5lee

    03/22/2022, 10:20 AM
    Which one is better? 1.
    class SomeThing {
        fun throwAnException(): Nothing { ... }
    }
    
    // ...
    val s: SomeThing = ...
    if (...) 
        s.throwAnException()
    2.
    class SomeThing {
        fun anException(): Exception { ... }
    }
    
    // ...
    val s: SomeThing = ...
    if (...) 
        throw s.anException()
    s
    s
    +3
    • 6
    • 6
  • s

    Stylianos Gakis

    03/24/2022, 9:25 AM
    Trying to use interface delegation and I found myself in a situation where I am not sure about if what I am trying to do is possible. More in thread 🧵
    e
    • 2
    • 6
  • a

    andodeki

    03/24/2022, 10:45 PM
    fun main() {
        var newList1 = listOf(listOf(1, "a", "b"), listOf(1, "a", "b"), listOf(1, "a", "b"))
        var newList = listOf(1, "b", "C" to newList1)
        var defaultList = listOf(1, "a", 'B' to newList)
    
        var a = defaultList[2]
    
    	print(a::class.java.typeName)  //kotlin.Pair
    }
    I need to access "newList1" but i cant since "defaultList" is a Pair
    how can i access via index or how can i construct to get this behaviour
    n
    • 2
    • 1
  • j

    Jason5lee

    03/25/2022, 8:21 AM
    If you want a list or map that is expected to be immutable, which one of the solution will you use? 1. Accepts `List<T>`/`Map<K, V>` and let the caller ensures that it is immutable. 2. Accepts `List<T>`/`Map<K, V>` and use the `.toList`/`toMap` version. 3. Use the `ImmutableList`/`ImmutableMap` of
    kotlinx.collections.immutable
    . 4. Others. State in the comment.
    1️⃣ 3
    m
    k
    +2
    • 5
    • 6
  • j

    Jason5lee

    03/25/2022, 2:50 PM
    When should I use
    sealed interface
    or
    sealed class
    ?
    l
    a
    +4
    • 7
    • 11
Powered by Linen
Title
j

Jason5lee

03/25/2022, 2:50 PM
When should I use
sealed interface
or
sealed class
?
l

Luke

03/25/2022, 2:52 PM
My rule of thumb is to always use a
sealed interface
unless I need a constructor in the
sealed class
a

Alejandro Rios

03/25/2022, 2:53 PM
Most common use of a
sealed class
is to handle the states of a response
Failure/Success/Loading
e

ephemient

03/25/2022, 3:26 PM
sealed interface doesn't work with
@Serializable
at present, so I still default to
sealed class
unless there is a particular structure that can only be expressed as
sealed interface
👍 1
a

andylamax

03/25/2022, 11:48 PM
As @ephemient said, My go to approach is a sealed interface, unless I want to serialize then, I fallback to sealed class
e

ephemient

03/25/2022, 11:51 PM
that's the opposite of what I said :P
but that works too
https://github.com/Kotlin/kotlinx.serialization/issues/1576 is supposed to be fixed in Kotlin 1.6.20 so hopefully this won't be a necessary consideration in the future
s

Stephan Schroeder

03/28/2022, 7:10 AM
another nice property of
sealed interface
is that its implementing classes can be data classes, which is why sealed interfaces is my default. (good to know about the serializable restriction!)
e

ephemient

03/28/2022, 4:27 PM
data class can subclass (sealed) classes too, that's not a distinction
👍 1
ł

Łukasz Gendek

03/29/2022, 9:12 AM
with sealed interfaces the multi inheritance is allowed
e

ephemient

03/29/2022, 3:49 PM
yes, that would be the "unless there isa particular structure that can only be expressed as a `sealed interface`" in my previous message. but ultimately it's a mostly stylistic choice if you're not interoperating with Java
View count: 15