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

    david-wg2

    08/01/2019, 10:32 AM
    what is the best way to force the initialization of the fields on an object, ex
    object Config {
        val port = System.getenv("PORT") ?: 8080
    }
    b
    d
    +2
    • 5
    • 25
  • t

    tjohnn

    08/01/2019, 10:51 AM
    How can I make
    MutableList.map{ ... }
    to return
    MutableList
    instead of
    List
    m
    d
    • 3
    • 4
  • t

    tjohnn

    08/01/2019, 10:53 AM
    Is there no overhead calling
    toMutableList()
    again after mapping?
    m
    s
    k
    • 4
    • 8
  • o

    oday

    08/01/2019, 9:18 PM
    is there such a thing as diffing two objects?
    k
    r
    • 3
    • 3
  • r

    Rodrigo Silva

    08/02/2019, 4:37 PM
    Hello everyone. Is there any lib / framework similar to Microsoft Blazor?
    r
    • 2
    • 2
  • m

    Mike R

    08/04/2019, 11:21 PM
    I'd like to implement a queue of functions where a function can be added, called after x seconds, then removed. I don't want to have to specify what arguments are provided at call-time, but rather when they are being added to the queue... I believe I can define the queue like
    val queue: Queue<() -> Unit> = LinkedList()
    , but I don't think the Queue type will do what I need as I described above. Any recommendations?
    d
    m
    • 3
    • 11
  • m

    Mike R

    08/05/2019, 3:05 AM
    Where can I learn more about annotations? I'm reading through the docs on the Kotlin website but not finding much that's useful to me. Here's what I'm trying to do: I want to annotate functions that belong to a class. Those annotated functions when called should, instead of being executed right away, be added to a BlockingQueue that belongs to the containing class. So far I've figured out that I can make a
    annotation class Queueable
    with a Target of
    AnnotationTarget.FUNCTION
    . I'm not finding any documentation anywhere on how I can accomplish the rest of what I'd like to do though... In Python, for example, I can annotate a function and access it's arguments and other properties about it since the annotation wraps the function. Am I thinking about annotations incorrectly in Kotlin?
    a
    k
    • 3
    • 2
  • j

    Jérémy Touati

    08/05/2019, 5:36 AM
    open class SuperClass {
        override operator fun equals(other: Any?): Boolean {
            return super.equals(other)
        }
    }
    
    class ExtendedClass : SuperClass() {
        override operator fun equals(other: Any?): Boolean {
            return super.equals(other)
        }
    }
    Error:(9, 14) Kotlin: 'operator' modifier is inapplicable on this function: must override ''equals()'' in Any
    so apparently this doesn't compile unless I remove the
    operator
    keyword from `ExtendedClass`' implementation is this intended behavior? this seems... a bit weird and unintuitive to me
    k
    • 2
    • 4
  • d

    dharrigan

    08/06/2019, 8:10 AM
    Say I have an operation that may return a list of things or a null (interop with a library). What would be idomatic in kotlin to do something if the result is null or do another thing (map) if the result is not null (and contains elements). I'm thinking "either-or", as in either do a "default" operation if the result is null or the "or" operation if the result is not null and the list contains elements?
    d
    k
    m
    • 4
    • 4
  • p

    Pagoda 5b

    08/07/2019, 12:02 PM
    what if said function is an extension? e.g.
    fun OtherType.myFunc(...)
    , what's the syntax to choose the right super extension function for my override?
    d
    m
    e
    • 4
    • 11
  • m

    mathew murphy

    08/07/2019, 8:32 PM
    Suppose I have:
    abstract class AbstractClass (
      val a : String? = null,
      val b : String? = null,
      val c : String? = null,
      val d : String? = null,
      val e : String? = null,
      val f : String? = null,
      val g : String? = null
    )
    
    class MyClass (
      a, b, c, d, e, f, g,
      val h : String? = null,
      val i : String? = null
    ) : AbstractClass(
      a, b, c, d, e, f, g
    )
    Is there any kind of shorthand to avoid having to repeat a,b,c,d,e,f,g twice when defining the class?
    🇳🇴 2
    k
    u
    +3
    • 6
    • 15
  • m

    Mani

    08/10/2019, 3:27 PM
    Please help.
    d
    m
    • 3
    • 3
  • t

    tipsy

    08/10/2019, 8:44 PM
    is there any built in construct to deal with something like this?
    var initialized = false
    if (!initialized) {
        ...
        initialized = true
    }
    l
    k
    • 3
    • 33
  • m

    Mike R

    08/11/2019, 12:44 AM
    Anyone have articles/docs/samples of using OkHTTP/other network requests with coroutines? I'm trying to make a simple application that calls out to HTTPBin as a producer and sends the UUID responses back through a channel.
    t
    • 2
    • 1
  • t

    Tony Blundell

    08/12/2019, 10:03 AM
    fun doSomething() {
      // return instance of whatever is between the angle brackets below
    }
    
    val x = <MyType>doSomething()
    val y = <MyOtherType>doSomething()
    How should the signature of doSomething look?
    a
    b
    k
    • 4
    • 12
  • e

    Esa

    08/12/2019, 12:10 PM
    Or is there some other clever way to solve this?
    d
    j
    • 3
    • 28
  • t

    tjohnn

    08/15/2019, 10:06 AM
    Hi, anyone know why I am getting this as an error in kotlin but not in java? It is not allowing project to build either
    n
    d
    • 3
    • 6
  • s

    scottiedog45

    08/15/2019, 2:59 PM
    How would I do something like “I have a superclass (which has some logic in a lifecycle method that I want to trickle down to fragments), and I have an interface. I don’t want(?) the superclass to implement the methods in the interface, but everything that inherits from the superclass should implement the interface”.
    k
    s
    • 3
    • 4
  • a

    andym

    08/15/2019, 3:45 PM
    Can I pass an overloaded function as a parameter to another? Eg.,
    class Foo {
        fun bar(p1: Int)
        fun bar(p2: String)
    }
    Is it possible to reference one of the
    bar()
    overloads as a function argument?
    k
    • 2
    • 2
  • b

    bloder

    08/16/2019, 3:11 AM
    Hi all! I'm really new with compilers / kotlin compiler plugin / JVM bytecode then probably this is a very newbie question: is it possible with kotlin compiler plugin generate a function bytecode changing its name? Example I have this function:
    @TestAnnotation("bar") fun foo() {}
    And my plugin would change its bytecode to something like:
    fun foo_bar() {}
    And by doing that, compiler would support many functions with the same name? like:
    @TestAnnotation("bar") fun foo() {}
    @TestAnnotation("bar2") fun foo() {}
    @TestAnnotation("bar3") fun foo() {}
    d
    • 2
    • 1
  • j

    Jérémy Touati

    08/17/2019, 11:36 AM
    quick question, do you people (especially those working with IntelliJ): - always specify types explicitly, - never specify them when IntelliJ can infer them (since it will show them as hint text instead, at least with the IDE's default options) - something in-between? (like, only for interface/abstract/open methods' return types since they define a contract) i suppose it's mostly a matter of preference in some cases, but i find myself hesitating a bit when writing super simple/closed methods that return a boolean, or when using things such as
    List#toMutableList()
    (it seems a bit overkill to mark the resulting variable as a
    MutableList
    then), so i ended up going for the 3rd approach (aka, only for overridable stuff), but i was curious if there was some kind of consensus on this
    t
    • 2
    • 2
  • b

    bjonnh

    08/19/2019, 8:00 PM
    Is there a way to not have to say !! here?
    s
    • 2
    • 5
  • m

    Marcin Wisniowski

    08/22/2019, 12:38 AM
    Hello, IntelliJ doesn't allow me to run
    fun main() {}
    without the args array (works with it), why is that?
    s
    • 2
    • 17
  • f

    Florian

    08/22/2019, 10:23 AM
    can you use when in a string template like if else
    d
    • 2
    • 3
  • v

    Victor Pineda

    08/22/2019, 10:34 AM
    Hi, I would like to ignore a warning the compiler is throwing:
    Type mismatch: inferred type is Cursor? but Cursor was expected
    I can ignore it safely but de IDE does not provide me any suggestion to add a
    @SupressWarning`
    k
    • 2
    • 17
  • a

    Arian Stolwijk

    08/22/2019, 12:21 PM
    Hi, is ktlint the go-to formatter (the 'prettier' or gofmt) of kotlin? My team is starting to use kotlin, and such a tool would help a lot to keep things tidy 🙂
    a
    m
    +2
    • 5
    • 11
  • s

    Slackbot

    08/23/2019, 4:29 AM
    This message was deleted.
    s
    m
    • 3
    • 4
  • j

    Jack Englund

    08/24/2019, 12:45 AM
    So my understanding of extension functions is that you can add a function to an existing library as a static function. I've made this:
    fun System.currentTimeSeconds(): Long {
        return System.currentTimeMillis()/1000
     }
    and yet I can't do System.currentTimeSeconds(). Am I missing a concept or can you not do extension functions on System?
    d
    s
    +2
    • 5
    • 9
  • c

    chris.chen

    08/24/2019, 2:37 PM
    hi guys, one thing that i curious about
    and
    &&
    for example:
    val a = 3
            val b = 4
            val c = 5
            val d = 3
    
            val result1 = b == c && a == d
    
            val result2 = (b == c) and (a == d)
    1) the result2 if we write
    val result2 = b == c and a == d
    will not work. not sure why 2) For result1 because the b==c is false. so will not run a==d case. but result2 will get false false so finally will be false. which means result1 only perform one time check and result2 perform 2 times check. Is my understanding correct?
    k
    • 2
    • 5
  • j

    Jack Englund

    08/25/2019, 3:26 AM
    Is there a way to get the class of an object that extends another object? For example,
    class Car: Vehicle()
    ...
    getObjectChildClass(Car())
    ...
    fun getObjectChildClass(obj: Vehicle) {
         // From here I want the to know if it's a Car or some other class that extends vehicle, like Truck.
    }
    l
    t
    • 3
    • 8
Powered by Linen
Title
j

Jack Englund

08/25/2019, 3:26 AM
Is there a way to get the class of an object that extends another object? For example,
class Car: Vehicle()
...
getObjectChildClass(Car())
...
fun getObjectChildClass(obj: Vehicle) {
     // From here I want the to know if it's a Car or some other class that extends vehicle, like Truck.
}
or would I simply have to store a list of such classes, and loop through and check if its one of them?
l

Luca Nicoletti

08/25/2019, 5:51 AM
obj::class.java.name
j

Jack Englund

08/25/2019, 6:25 AM
I noticed that property but it gives it as a string, which poses more problems on turning that string into an actual reference to the class. I figured out a work-around.
l

Luca Nicoletti

08/25/2019, 6:28 AM
Which is?
j

Jack Englund

08/25/2019, 6:54 AM
I made an Enum that gets stored in the child object. I dont get the class directly from this but with some other changes (too much to explain), I'm able to do what I needed.
t

Thomas

08/25/2019, 8:25 AM
Why don't you just use a type check? What do you want to do with the class? https://kotlinlang.org/docs/reference/typecasts.html
j

Jack Englund

08/26/2019, 12:09 AM
I'm storing various child objects in a
HashMap<DataType, Packet>
. I'm using the DataType enum beacuse I have X amount of classes that might be stored as a Packet. Originally I had a helper method,
classToDataType()
, which I wanted to give a class, and then have it return the data type. I could've done type check but then I would have to make a list of possible classes and check every one. Given that it's part of caching I dont want to have to loop a potentially large list every time.
t

Thomas

08/26/2019, 6:55 AM
You could use `sealed class`es in a when statement.
View count: 5