https://kotlinlang.org logo
Docs
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
  • j

    Justin Fiedler

    08/09/2021, 2:26 PM
    Hi all, I am attempting to make a generic abstract class for Plugin's whose subclasses can enforce strongly typed method parameters. I was able to get this mostly working using the following but have hit issues when trying to iterate over the concrete Plugin subclasses in a generic manner. Here is a short(ish) sample of what I am attempting. Any suggestions on how to approach this? Thank you in advance!
    • 1
    • 3
  • g

    Gaurav Singh

    08/09/2021, 6:06 PM
    Can anybody tell me, if this is possible?
    c
    d
    • 3
    • 2
  • p

    PriNova

    08/09/2021, 9:21 PM
    Hello Kotliners, I'm new to Kotlin but longtime experience with Java, C(++). My host is an Android Tablet (linux aarch64) with termux (and nearly full linux dist/terminal emulator) as dev environment and have no issue to use NDK with clang 12.0.1 for crosscompiling and latest GraalVM working perfectly. I have no Desktop/Notebook etc (Digital Nomade). Then I tried Kotlin/Native without success, because of incompatibility of my OS. Is there a workaround for my platform? What about rebuilding the kotlin/native module from source and hacking my OS into the Platform.kt? My use-case is to work with executables/libraries written in Kotlin with cinterop. Thank you in advance
    s
    • 2
    • 2
  • n

    napperley

    08/10/2021, 2:24 AM
    Very curious to know what techniques Kotliners use for managing resources. In the example below I manage a resource via the Closable technique:
    interface Closable {
      val isClosed: Boolean
    
      fun close()
    }
    
    class ResourceX : Closable {
      val isClosed: Boolean
        get() = _isClosed
      private var _isClosed = false
    
      fun close() {
        if (!_isClosed) {
          // Do cleanup here.
          _isClosed = true
        }
      }
    
      fun operation() {
        if (_isClosed) throw IllegalStateException("ResourceX is closed")
        // Do stuff related to the operation here.
      }
    }
    e
    • 2
    • 3
  • e

    ephemient

    08/10/2021, 3:59 AM
    This compiles in Kotlin 1.5.21 but fails to typecheck in Kotlin 1.5.30-RC:
    fun f(l: MutableList<String>) {}
    @ExperimentalStdlibApi
    val l: List<Any> = buildList {
        javaClass
        f(this)
    }
    Did something change with builder inference?
    r
    d
    v
    • 4
    • 4
  • f

    Florian

    08/10/2021, 10:41 AM
    I want to turn an
    Int?
    into a
    String?
    but if the
    Int?
    is
    null
    I don't want to have a literal
    "null"
    String, I want the string value to be
    null
    . Is there an operator for this or do I have to check it manually?
    a
    d
    • 3
    • 7
  • e

    emwy

    08/10/2021, 12:20 PM
    Would be great if there was a modifier to make a variable have public getter but private setter... So, instead of this:
    var a = 2
    private set
    we could write something like
    local var a = 2
    b
    r
    h
    • 4
    • 6
  • j

    Jeremy Soles

    08/10/2021, 4:58 PM
    I believe it cannot handle the success, failure response from the Kotlin API.
    m
    • 2
    • 2
  • r

    Rahul Mishra

    08/10/2021, 5:02 PM
    A hackathon exclusively for Indian developers? Solana's got you covered. 'Building out Loud' is a three-week-long hackathon hosted by Solana in partnership with Superpumped, Devfolio, and a great panel of judges. Solana’s blazing fast blockchain allows you to deploy apps that can scale to a billion users. This hackathon will provide an incredible platform for developers and students to launch their projects on Solana and dabble with all things blockchain. Are you up for the challenge? What's in it for you? 📍 Win prizes worth $80,000 📍 Launch a global product 📍 Pitch to and raise capital from Solana Foundation, Balaji and other investors Register here --> https://buildingoutloud.solana.com
    :not-kotlin: 14
    k
    • 2
    • 1
  • a

    Asq

    08/10/2021, 9:12 PM
    General question for someone with greater wisdom. This code (run with kotlin 1.5)
    1:    val aut = setOf(2, 3, 1, 4, 0)
    2:    print("$aut")
    3:    val aux2a: List<Int> = aut.dropWhile{ 2 < it }
    4:    a2.containsAll(aux2a) shouldBe true
    5:    (aux2a.size < a2.size) shouldBe true
    fails (i.e.
    (aux2a.size < a2.size)
    is
    false
    ) at line 5. the documentation for
    dropWhile
    says :
    Returns a list containing all elements except first elements that satisfy the given predicate.
    I would have expected that at least item
    3
    (from line 1) xor item
    4
    would have been dropped. Perhaps both under certain circumstances (ordering is not a property of
    Set
    ). What is the expected behavior of
    dropWhile
    for a Set?
    r
    p
    e
    • 4
    • 11
  • u

    Ubinyou

    08/11/2021, 2:48 AM
    hello guys
    r
    • 2
    • 1
  • j

    Javier

    08/11/2021, 7:49 AM
    Should this channel be read only for almost everyone and be used for announcements or something so?
    🙏 1
    ❤️ 1
    g
    • 2
    • 2
  • t

    thana

    08/11/2021, 9:32 AM
    out of curiosity: is there a nice way to abbreviate
    fun foo(): Boolean {
      val bool = isConditionMet()
      if (bool) {
         log(…)
      }
       return bool
    }
    j
    d
    +2
    • 5
    • 12
  • m

    Mark

    08/11/2021, 12:58 PM
    “Cascade if can be replaced with when” warning but sometimes it’s a false positive, for example if I have an
    if
    condition (at least 3 branches) where the checks are things like
    Build.VERSION.SDK_INT > 12
    and then branch depends on such a later SDK level. How to suppress this warning?
    c
    e
    • 3
    • 11
  • s

    smit01

    08/11/2021, 5:14 PM
    Where can I learn more about kotlin compiler? Under the hood architecture and all.
    t
    • 2
    • 1
  • b

    Bart

    08/11/2021, 7:18 PM
    Hello All! Im looking for way to create app using ktor and kotlin/js. The catch is that i want to create web app based on windows(drag and drop items that can be minimalize or close) and im totally confused with a way to use routing there. Did someone can help me understand that concept?
    b
    r
    • 3
    • 3
  • s

    shama

    08/11/2021, 9:22 PM
    Is there an existing cached computed property pattern in Kotlin? For example:
    var firstName: String = "Charlie"
    var lastName: String = "Brown"
    val fullName: String by lazy {
      "$firstName $lastName"
    }
    println(fullName) // Charlie Brown
    
    firstName = "Snoopy"
    // Let "fullName" know it will need to recompute the next time it is accessed
    println(fullName) // Snoopy Brown
    I’m currently going down writing my own
    ReadWriteProperty
    for it but wondering if there is an existing pattern for this already? Thanks!
    a
    • 2
    • 2
  • f

    Florian

    08/11/2021, 11:49 PM
    Why does this break smart cast 🤔
    val showSelectNewTaskConfirmationDialog = newTask != null
    if (showSelectNewTaskConfirmationDialog) {
        // smart cast for newTask here not working
        [...]
    }
    e
    d
    • 3
    • 5
  • f

    franztesca

    08/12/2021, 8:08 AM
    I'm trying to make extensions that wraps part of the behavior of interfaces without changing the interface signature. Not finding a scalable solution though. Anyone finding a decent solution would be awesome 🤗 Problem:
    interface Counter {
        fun add()
        fun remove()
    }
    
    // We have some interfaces extending counter
    interface MyCounter : Counter {
        fun doStuff()
    }
    
    interface MyOtherCounter : Counter {
        fun doOtherStuff()
    }
    
    // Implements counter by wrapping a counter and calling add/remove twice.
    class DoubleCounter(val baseCounter: Counter) : Counter {
        override fun add() {
            baseCounter.add()
            baseCounter.add()
        }
        override fun remove() {
            baseCounter.remove()
            baseCounter.remove()
        }
    }
    
    // These two are okay, but very boilerplate and non-scalable
    fun MyCounter.double(): MyCounter {
        val double = DoubleCounter(this)
        return object : MyCounter by this {
            override fun add() = double.add()
            override fun remove() = double.remove()
        }
    }
    fun MyOtherCounter.double(): MyOtherCounter {
        val double = DoubleCounter(this)
        return object : MyOtherCounter by this {
            override fun add() = double.add()
            override fun remove() = double.remove()
        }
    }
    
    // This is illegal, is there any way to do this or similar?
    inline fun <reified T: Counter> T.double(): T {
        val double = DoubleCounter(this)
        return object : T by T {
            override fun add() = double.add()
            override fun remove() = double.remove()
        }
    }
    t
    • 2
    • 3
  • k

    K Merle

    08/12/2021, 12:46 PM
    when (result) {
        Result.Loading -> {}
        is Result.Success -> SomeScreen(data= (dataResult as Result.Success<List<SomeData>>).value)
        is Result.Error -> {}
    }
    How do I prevent casting type on Success? My Result class
    sealed class Result<out T> {
        object Loading : Result<Nothing>()
        data class Error(val message: String) : Result<Nothing>()
        data class Success<T>(val value: T) : Result<T>()
    }
    i
    m
    i
    • 4
    • 12
  • a

    Alina Dolgikh [JB]

    08/13/2021, 7:10 AM
    📣 Hi everyone <!here>! This is a follow-up on our change proposal for this Slack space. First of all, thank you to everyone who shared their feedback and applied to be a moderator. All of us in the community appreciate it! 🙏 Next steps: 1. We’ll rename #general to #announcement and make it read-only starting August 18 (Wednesday). #getting-started will replace #general as a channel where folks who are new to Kotlin (and this Slack space) can ask questions. Any newcomer will automatically join the #getting-started channel. 2. We’ll be archiving duplicated, private, and unauthorized shared channels starting August 18. All attendees and owners will get notifications 72 hours prior to archiving.
    🎉 3
    🆗 4
    ✔️ 7
    :kotlin-intensifies: 5
    ✅ 58
    :thumbsup_all: 6
    :party-parrot: 22
    😍 5
    b
    e
    +5
    • 8
    • 8
  • a

    althaf

    08/13/2021, 1:17 PM
    Hi
    enum class Role(val letter: Char) {
        APPROVER('U'),
        ADMIN('D'),
        INQUIRER('R'),
        OPERATOR('O');
    }
    we have create this enum for code readability and we don't have direct control over how server is returning constants for the user roles, so they have done it this way 'U' , R etc apiRespose.role = "U" Role.valueOf(apiResponse.role) will not work ,as it is expecting 'APPROVER' as input . How can i achieve same benefit of Role.valueOf( ) wrt ot the 'letter' attribute in the enum
    c
    h
    • 3
    • 5
  • h

    heisenberg

    08/13/2021, 1:42 PM
    Good day, I'm using reflection method to handle the last call method example
    fun foo(name: String) {
      lastCallMethod = ::foo
    }
    Now I want to call the method
    lastCallMethod
    May I ask if there is a way to retrieve the
    name
    String that pass using reflection?
    z
    e
    • 3
    • 3
  • a

    althaf

    08/14/2021, 4:20 PM
    Hi, how do we pass the string parameter 'emessage' to the exception instance
    fun String?.throwOnEmptyOrNull(emessage: String, exceptionClass: Class<out Exception>): String {
        return this.takeIf { !it.isNullOrBlank() } ?: throw exceptionClass.newInstance()
    }
    val ss : String? = null
    println("test 1 ${ss.throwOnEmptyOrNull("roles can't be empty or not", IllegalArgumentException::class.java)}")
    This is working for me, however i'm stuck at passing the message to exception
    d
    e
    • 3
    • 14
  • j

    Joshua F

    08/15/2021, 8:21 AM
    Just me or does the left side on the docs not show anything? https://kotlinlang.org/docs/home.html
    m
    • 2
    • 2
  • e

    Erik

    08/15/2021, 8:38 AM
    With kotlin 1.5.21 installed on my path, in my shell when I run
    kotlin
    and then at the REPL prompt I type
    (-1).toUInt()
    or
    1u - 2u
    , then the result is
    kotlin.UInt = -1
    . Is that expected?
    kotlin.UInt
    ranges from 0 to 2^32-1, but can it be rendered as negative too somehow? Or is
    kotlin.UInt = -1
    actually equal to
    2^32-1
    ?
    e
    a
    • 3
    • 13
  • j

    Jason5lee

    08/15/2021, 10:27 AM
    How to supress unused warning for the public members only?
    e
    • 2
    • 1
  • c

    Cicero

    08/15/2021, 11:37 AM
    Who moderates the community?
    d
    • 2
    • 1
  • s

    Strum355

    08/15/2021, 12:47 PM
    Is it possible with contracts to imply the return type of a method to be of type T where T is a reified type parameter, so that smartcast is possible outside the method?
    d
    • 2
    • 2
  • m

    Mark

    08/16/2021, 4:02 AM
    Any thoughts on this approach (companion object of interface implementing interface) to inject an instance to be used throughout app?
    // common module
    interface Brand {
        val foo: String // plus lots more properties and funs
    
        // implement Brand so usage like Brand.foo instead of Brand.INSTANCE.foo
        companion object : Brand {
            // this must be set very early in Application.onCreate()
            // why not use DI? Because sometimes we need access to Brand before DI has finished setting up
            lateinit var INSTANCE: Brand
    
            override val foo: String
                get() = INSTANCE.foo
        }
    }
        
    // brand module (dependency on common module)
    // different brand modules for different product flavors
    object ActualBrand : Brand {
        override val foo: String
            get() = "actual brand"
    }
    
    fun Brand.Companion.init() {
        INSTANCE = ActualBrand
    }
    
    // app module (dependencies on brand and common modules)
    class MyApplication : Application() {
        override fun onCreate() {
            super.onCreate()
            Brand.init() // note: we do not need to hardcode ActualBrand
            // proceed to DI initialisation
        }
    }
    t
    c
    • 3
    • 8
Powered by Linen
Title
m

Mark

08/16/2021, 4:02 AM
Any thoughts on this approach (companion object of interface implementing interface) to inject an instance to be used throughout app?
// common module
interface Brand {
    val foo: String // plus lots more properties and funs

    // implement Brand so usage like Brand.foo instead of Brand.INSTANCE.foo
    companion object : Brand {
        // this must be set very early in Application.onCreate()
        // why not use DI? Because sometimes we need access to Brand before DI has finished setting up
        lateinit var INSTANCE: Brand

        override val foo: String
            get() = INSTANCE.foo
    }
}
    
// brand module (dependency on common module)
// different brand modules for different product flavors
object ActualBrand : Brand {
    override val foo: String
        get() = "actual brand"
}

fun Brand.Companion.init() {
    INSTANCE = ActualBrand
}

// app module (dependencies on brand and common modules)
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        Brand.init() // note: we do not need to hardcode ActualBrand
        // proceed to DI initialisation
    }
}
t

Tomasz Krakowiak

08/16/2021, 4:07 AM
Why not inject brand via DI, if you use one? Or maybe make it property of an Application?
m

Mark

08/16/2021, 4:08 AM
I need it during DI initialisation.
Application
not always available
Hmm, just trying out the code, and the problem is that
Application.onCreate()
is being called too late. I’m using Android AppInitializers which are triggered earlier, so next step is to investigate: https://proandroiddev.com/app-startup-under-the-hood-with-koin-library-example-380e188568ad But still, I’m interested in general thoughts about implementing an interface with the interface’s companion object.
t

Tomasz Krakowiak

08/16/2021, 4:47 AM
Maybe having them both in DI and Application property would be solution? I'm not sure what technologies you're using and how they work (long time since I coded anything for android), but I would definitely try to avoid having something that should be Application scope as global.
m

Mark

08/16/2021, 4:48 AM
Right, I don’t have any intention to have an Application property like that.
c

Colton Idle

08/16/2021, 1:53 PM
Personally, I would skip the initializer library and do everything in oncreate.
m

Mark

08/16/2021, 1:55 PM
I believe
Application.onCreate()
occurs after
ContentProvider
initialisation
c

Colton Idle

08/16/2021, 1:57 PM
Correct. Just stop using CP init. And disable other libraries from doing it (like firebase)
View count: 3