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
getting-started
  • t

    thhh

    04/07/2021, 2:03 PM
    Are lists in Kotlin random access data structure and is it the same case for the list in Java? Also, how does one verify if the list in random-access collection or not practically through code sample?
    r
    m
    +2
    8 replies · 5 participants
  • l

    Lynette Midy

    04/07/2021, 2:39 PM
    Noob here to kotlin, thanks for the add. My focus is more server side, learning about ktor and exposed.
    👋🏾 1
    👋 6
    b
    s
    2 replies · 3 participants
  • d

    Daniele B

    04/07/2021, 4:45 PM
    is there any way to simplify this?
    update( B(firstField = objA.name, secondField = objB.surname) )
    into something similar to this? (it doesn’t work)
    update( ::objA )
    given that the two classes have the same structure but just different property names? so that I don’t need to manually specify each field?
    val objA = A("John", "Walker")
    
    fun update(obj : B) {
        ...
    }
    
    data class A (
        val name : String
        val surname : String
    )
    
    data class B (
        val firstField : String
        val secondField : String
    )
    N.B. I cannot modify the classes definition, by extending or implementing interfaces
    r
    e
    9 replies · 3 participants
  • h

    hisham bin awiad

    04/08/2021, 10:02 AM
    i have task in
    Codewars
    : and i found tow same ways with little diff so i need help : how can know what is the beast code ? any tool to do that ? what easy way and good performance ? Is the
    build time completed
    when run app , can relies on it or no
    v
    m
    3 replies · 3 participants
  • t

    thhh

    04/09/2021, 12:04 PM
    How to calculate the number of public, private, internal, protected methods and classes from a public or internal package?
    s
    3 replies · 2 participants
  • m

    Mark

    04/10/2021, 4:44 AM
    When overriding a function with a nullable return value, is there any way to declare the return value is always null (in the signature)?
    n
    e
    3 replies · 3 participants
  • t

    thhh

    04/10/2021, 3:11 PM
    Help me understand what is meant by "Case 2 doesn’t work with mutating properties, instead in case 1 the variable 
    it
     is always not null." The text in quotation was in response to: What is actually the difference and what is the preferred to use: Case 1:
    variable?.let { //... }
    Case 2:
    if (variable != null) { //... }
    e
    n
    8 replies · 3 participants
  • t

    thhh

    04/12/2021, 1:55 PM
    What is this syntax?
    "creating and linking nodes" example {
    I don't understand how there's a string
    "creating and linking nodes"
    then after a
    example
    Please explain!
    fun main() {
        "creating and linking nodes" example {
            val node1 = Node(value = 1)
            node1.next = node3 // shortened for brevity
            println(node1)
        }
    }
    d
    m
    +1
    15 replies · 4 participants
  • t

    thhh

    04/12/2021, 2:34 PM
    I often need to add break points to different small code in a file. The usecase is to see the entire flow of code using breakpoint, but now I need to manually add many breakpoints to intellij IDEA. Is there a way to add breakpoint to all the possible code lines at once so I can simply do that and observe the code flow?
    y
    r
    3 replies · 3 participants
  • f

    Filipe Duarte

    04/12/2021, 6:36 PM
    What’re the main differences between Kotlin and Scala? I mean, I started using Kotlin this weekend and feel many similarities for an intermediate programmer between both languages.
    n
    r
    +1
    16 replies · 4 participants
  • t

    tipsy

    04/12/2021, 9:09 PM
    i'm trying to put a
    java.lang.Object
    in a map with type
    Map<Class<*>, Any>
    , i'm getting the following error message that i'm not able to figure out:
    Required type: capture of ? extends Object
    Provided: Object
    d
    9 replies · 2 participants
  • t

    trofman

    04/13/2021, 6:08 AM
    hi! what is kotlin default source sets directories?
    t
    e
    3 replies · 3 participants
  • t

    Travis Griggs

    04/13/2021, 9:58 PM
    Are there a set of rules people follow about where to declare instance variables in Kotlin? Ideally, I just want them in a single terse vertical list, so every time I look at a class declaration I see something like:
    TheNewClass:TheParentClass {
    var a:Foo
    var b:Bar
    var c:Baz
    }
    But primary constructors make it more interesting. Now I can declare them right in one line, which I don't mind when it's just that guy, something like:
    data class Point<T>(val x:T, val y:T) { }
    Now I've got to decode two types of object declarations when looking at them. But then I can mix and mash them:
    class BLEConduit(val peripheral:BLEPeripheral):ConnectionConduit {
       var sendBuffer = ubyteArrayOf() 
       var receiveBuffer:UByteArray? = null
    So now I'm having to parse (and rationalize) two lists, to get at what the "guts" of an object is. And if I mix parameters without val/var in the primary constructor, any conciseness really breaks down. Are there a set of rules/guidelines others follow on when to put what where? To me, Kotlin's properties/init/constructors feels very evolutionary, like they started in one place, and then evolved things, but left backwards compatibility in place, and now there's less of a clear/idiomatic way to declare what an object is and how it gets initialized.
    👍 1
    n
    c
    +1
    7 replies · 4 participants
  • t

    tipsy

    04/16/2021, 8:18 PM
    in ran into an issue with default arguments
    myFunc(p1: String, p2: Consumer<*>, p3: String = "") {}
    // is not the same as 
    myFunc(p1: String, p2: Consumer<*>) { myFunc(p1, p2, "") }
    myFunc(p1: String, p2: Consumer<*>, p3: String) {}
    the compiler does not allow you to use trailing lambdas if you use default arguments i'm not really sure if it's an issue, but did seem odd to me
    n
    r
    22 replies · 3 participants
  • u

    ushort

    04/16/2021, 8:33 PM
    Need help with compiling on IJ. I have gradle setup where module b implements/depends on module a. I imported a class from module a inside module b and gradle builds fine and IJ editor picks it up. But as soon as I try delegating build to IntelliJ, it throws compilation error, unable to resolve the import of class from module a. I checked dependencies for module b inside Project Structure -> Modules and module a was indeed there. Everything checks out but just can't build. Currently using IntelliJ 2020.3.3, IntelliJ Kotlin Plugin 203-1.4.32-release-IJ7148.5, and kotlin gradle plugin/stdlib 1.4.32
    2 replies · 1 participant
  • c

    Colton Idle

    04/17/2021, 1:52 AM
    I feel stupid. I try to write documentation on top of my class like so
    /**
    * This class does this or that
    *
    but I always want to link to other classes or methods to help my team easily navigate to places that I reference, but I can never get it to work correctly. I also tried to search online for how to write common documentation like this, but I still can't get it to work. Apparently I just put a class name in brackets [] but when I pull up the documentation I can't click on it to navigate to that class. Does anyone know of like a nice crash course in documenting in kotlin code? Thank you!
    u
    e
    10 replies · 3 participants
  • d

    DMITRY.

    04/19/2021, 1:29 PM
    abstract class Task<T : Enum<T>>(
        @field:Id
        @field:Indexed
        open val id: ObjectId?,
        open val group: Group
    )
    
    data class Change(
        override val id: ObjectId?,
        override val group: Group
    ) : Task<Status>(id, group)
    
    enum class Group {
        FIRST,
        SECOND
    }
    
    -----
    
    
    Ambiguous field mapping detected! Both private final ru.whatever.kek.tracker.model.Group ru.whatever.kek.tracker.model.task.Task.group and private final ru.whatever.kek.tracker.model.Group ru.whatever.kek.tracker.model.task.Change.group map to the same field name group! Disambiguate using @Field annotation!
    but if I use @Field annotation I get this in MongoDB:
    d
    3 replies · 2 participants
  • m

    Michael Böiers

    04/19/2021, 4:39 PM
    Rookie question. If I want to provide some code in a class that just returns something, how do I do it? a) Define a function naming the data returned:
    fun parsedElements()
    b) Define a function naming the data returned prefixed with get (since as per coding conventions functions should incorporate a verb):
    fun getParsedElements()
    c) Define a read-only property naming the data returned:
    val parsedElements: List<String> get() = …
    What’s considered best practice, does it depend on “how dynamic” the code is?
    n
    g
    13 replies · 3 participants
  • c

    Colton Idle

    04/19/2021, 5:20 PM
    Creating a singleton in kotlin (object/companion) just for constants (like some INT codes my team uses in our files) seems wrong. What do people typically do? Just have top level constants? Or do people really just create companion objects?
    v
    n
    +2
    17 replies · 5 participants
  • a

    andym

    04/22/2021, 3:07 PM
    I’d like a convenience extension to return true when a nullable string is not null, and not blank — neither should be processed. After the extension returns true for an immutable, I don’t want to have to have to
    !!
    it. But it seems I can’t use “this” in a contract:
    contract {
            returns(true) implies (this != null)
        }
    
        return !this.isNullOrBlank()
    Is there a way to do this?
    y
    n
    +1
    7 replies · 4 participants
  • c

    Cath

    04/23/2021, 11:00 AM
    how would I go about loading an image from a test directory's resources in kotlin? Tried it using the class loader but ran into a NPE:
    var byteArray = this::class.java.classLoader.getResource("abc.jpg").readBytes()
    j
    t
    +1
    8 replies · 4 participants
  • d

    dave08

    04/25/2021, 12:57 PM
    Is the only reason to use 
    : Any
     in generics to prevent nulls?
    I have something like:
    interface UseCase<in Request : Any, out Response : Any> {
        suspend fun execute(request: Request): Response
    }
    and in certain cases I need the Response to be nullable, and in others not. How can I implement such a Spy:
    class UseCaseSpy<Request : Any, Response>(
        private val returnIfNoResponse: (suspend (Request) -> Response)? = null,
        private val allowNullResponse: Boolean = false
    ): UseCase<Request, Response> {
        var request: Request? = null
        var responseToReturn: Response? = null
    
        override suspend fun execute(request: Request): Response {
            this.request = request
    
            val response =  responseToReturn ?: returnIfNoResponse?.invoke(request)
    
            if (response == null && !allowNullResponse)
                error("Either responseToReturn or returnIfNoResponse needs to be provided.")
    
            return response
        }
    }
    execute
    needs to return
    Response?
    whether my actual type is nullable or not... so it just doesn't compile
    y
    6 replies · 2 participants
  • s

    Somesh

    04/26/2021, 4:39 PM
    Hello, I am getting a response something like this where
    status
    ,
    message
    &
    data
    keys will remain the same across the different API responses & only the content inside the
    data
    JSON object will change, in this example, I have a JSON object with a
    member
    key in other response I can have
    tournament
    key.
    {
      "status": true,
      "message": "Success",
      "data": {
        "member": {
          "id": 21,
          "emailAddress": "<mailto:abc@xyz.com|abc@xyz.com>",
          "firstName": "ABC"
        }
      }
    }
    Currently, I am making use of generics and doing something like this
    data class SignInResponse(
        val `data`: Data<Member>
    ) : BaseResponse()
    and
    BaseResponse
    class has common JSON keys that I am getting, Here I'm using generics in data class passing the JSON class that is changing.
    open class BaseResponse {
        val status: Boolean  = false
        val message: String  = UNDEFINED
    }
    
    
    @Keep
    data class Data<T>(val actualData: T)
    But this approach is incomplete because the above code will expect a JSON key
    actualData
    but here JSON key can be a
    member
    ,
    tournament
    , or anything. How can I pass the class in
    Data
    class so that it can support the above JSON response?
    r
    6 replies · 2 participants
  • s

    skwalking

    04/27/2021, 8:07 AM
    I was doing Using State in Compose "codelab" (Android) there was a code
    TodoItemInlineEditor(
        item = currentlyEditing,
        onEditItemChange = onEditItemChange,
        onEditDone = onEditDone,
        onRemoveItem = { onRemoveItem(todo) }
    )
    In my case I wrote in this way:
    TodoItemInlineEditor(
        item = currentlyEditing,
        onEditItemChange = {onEditItemChange},           ............................difference 1 writing inside {}
        onEditDone = {onEditDone},                       ............................difference 2 writing inside {}
        onRemoveItem = { onRemoveItem(todo) }
    )
    by using onEditItemChange and onEditDone inside {} somehow made my app to stop working. So what is the difference by writing inside {} and without {} ? onEditItemChange , onEditDone and onRemoveItem(todo) are lamda callback from:
    @Composable
    fun TodoScreen(
        items: List<TodoItem>,
        currentlyEditing: TodoItem?,
        onAddItem: (TodoItem) -> Unit,
        onRemoveItem: (TodoItem) -> Unit,
        onStartEdit: (TodoItem) -> Unit,
        onEditItemChange: (TodoItem) -> Unit,
        onEditDone: () -> Unit
    ) {
    .....
    .....
    TodoItemInlineEditor(
        item = currentlyEditing,
        onEditItemChange = onEditItemChange,
        onEditDone = onEditDone,
        onRemoveItem = { onRemoveItem(todo) }
    )
    ....
    ....
    }
    r
    1 reply · 2 participants
  • j

    John Pena

    04/27/2021, 3:48 PM
    hey folks, i’m writing a sprint boot web server in kotlin and i’ve come across a library (written in java) that has a
    synchronized
    block, do i have to do anything special to call this function and ensure it completes?
    m
    1 reply · 2 participants
  • s

    Slackbot

    04/27/2021, 4:50 PM
    This message was deleted.
    c
    j
    2 replies · 3 participants
  • t

    thhh

    04/27/2021, 4:51 PM
    I heard someone say the reason why Kotlin dont use Java 8 Streams is due to Android not supporting Streams, that;s why Kotlin uses sequences and not Streams. Q: Why Android cannot use Java 8 Stream and what's the relation between Streams and Kotlin.
    c
    1 reply · 2 participants
  • e

    ermac10k

    04/28/2021, 9:35 AM
    Hello! who can explain what is a main aim of the ‘const’ word? i know the mechanism (compile time and no getter method). But i cannot understand when it is useful.
    j
    c
    +3
    28 replies · 6 participants
  • j

    Joe

    04/29/2021, 5:11 PM
    dealing with calling a java based fluent/builder api conditionally -- right now i've gotten to:
    return Builder.builder().withIntParam(intParam).let {
         if (booleanFlag) {
               it.withBoolean()
         } else {
               it
         }
    }.build()
    anyone have a better pattern for something this? assuming the builder is mutable/side-effecty can change it to something like:
    return ....apply {
       if (booleanFlag) { withBoolean() }
    }
    which is a little cleaner but might not work with all builder impls?
    a
    m
    +1
    4 replies · 4 participants
  • a

    apahl

    05/01/2021, 10:33 AM
    Anyone got a clue what might be wrong with my setup, that I get the following error for this minimal code:
    fun main() {
    val (a, b) = Pair(1, "x")
    }
    Cannot access '<http://kotlin.io|kotlin.io>.Serializable' which is a supertype of 'kotlin.Pair'. Check your module classpath for missing or conflicting dependencies
    I am using Kotlin 1.4.32 and Java 11. Thanks a lot.
    1 reply · 1 participant
Powered by Linen
Title
a

apahl

05/01/2021, 10:33 AM
Anyone got a clue what might be wrong with my setup, that I get the following error for this minimal code:
fun main() {
val (a, b) = Pair(1, "x")
}
Cannot access '<http://kotlin.io|kotlin.io>.Serializable' which is a supertype of 'kotlin.Pair'. Check your module classpath for missing or conflicting dependencies
I am using Kotlin 1.4.32 and Java 11. Thanks a lot.
Turns out, I was missing the stdlib in the dependencies section:
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.32")
Doh.
:rubber_duck: 1
View count: 2