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

    poohbar

    06/14/2019, 3:28 PM
    (argument as List<String>?)?.orEmpty()
    intellij is highlighting the
    ?.
    as "This call is useless" why is it useless?
    t
    a
    p
    • 4
    • 7
  • m

    Mario

    06/16/2019, 6:50 PM
    guys i am new here what is the best place to learn kotlin and ye expect kotlin
    j
    d
    +2
    • 5
    • 4
  • c

    Chi

    06/18/2019, 9:02 PM
    is it a better way of doing this? I would expect something like a
    guard
    in swift
    -.kt
    l
    • 2
    • 1
  • c

    Chi

    06/18/2019, 9:11 PM
    Can kotlin have function to do this?
    -.kt
    d
    l
    +2
    • 5
    • 7
  • h

    hooliooo

    06/19/2019, 10:07 AM
    I’ve created an intellij project with Kolin-JVM used. But when I type in GlobalScope to do coroutine stuff its pointing to javax.xml.bind.JAXBElement how can I solve this?
    t
    • 2
    • 3
  • f

    Florian

    06/19/2019, 7:57 PM
    can someone explain why a++ works in a string template but not a+=1
    t
    • 2
    • 2
  • k

    karelpeeters

    06/19/2019, 9:13 PM
    To simplify the compiler code.
    :thread-please: 4
    f
    • 2
    • 34
  • i

    Ifvwm

    06/20/2019, 2:52 AM
    if I want to use generics in function definition, do I must need to put a <T> before the function's name like fun <T> whatever(x: T, y: T) ?
    k
    s
    • 3
    • 2
  • o

    Obaid Jatoi

    06/20/2019, 7:08 AM
    Hi guys, I want to start kotlin multiplatform i want to make a shared network library which can be used in android, IOS and web like JS etc, can you please give me a tutorial or anything which covers all platform?
    g
    j
    • 3
    • 6
  • e

    elaborate tissue

    06/20/2019, 3:09 PM
    how can I get a reference to a top level function from a string, e.g. the name of the function
    😱 3
    a
    k
    • 3
    • 4
  • h

    Hullaballoonatic

    06/20/2019, 6:46 PM
    can i instantiate
    class Foo
    from
    Foo::class
    in any way?
    s
    d
    +2
    • 5
    • 86
  • f

    Florian

    06/20/2019, 7:16 PM
    is there any specific reason for that
    d
    a
    • 3
    • 10
  • f

    Florian

    06/20/2019, 9:31 PM
    This might be a dumb question but where are the method bodies for the operators functions inside Primitives.kt
    k
    • 2
    • 22
  • m

    matt tighe

    06/20/2019, 10:34 PM
    is it possible to add annotations to variables defined in interfaces? i.e
    interface foo {
        @StringRes val text: Int
    }
    m
    • 2
    • 2
  • p

    poohbar

    06/21/2019, 3:23 PM
    TIL that
    MyClass::class.sealedSubclasses
    does not return the classes in the order they were defined as opposed to
    MyEnum.values()
    in Java. Bit me!
    r
    i
    t
    • 4
    • 3
  • f

    Florian

    06/21/2019, 8:08 PM
    one thing I don't get about REPL: Since it evaluates expressions, shouldn't "print("Hi")" display "Unit" instead of "Hi"?
    d
    • 2
    • 6
  • f

    Florian

    06/21/2019, 8:26 PM
    In Kotlin, can every expression (theoretically) be used as a standalone statement? Java doesn't allow putting 1 + 1; into a line but in Kotlin that works
    d
    • 2
    • 7
  • f

    Florian

    06/22/2019, 10:56 AM
    In Kotlin, assignments are not expressions. But aren't increment and decrement operators also assignments technically?
    k
    t
    • 3
    • 6
  • a

    am

    06/23/2019, 10:58 AM
    How do we add generic class as Map value ? I am defining class named
    abstract class CardHolder<T:RecyclerView.ViewHolder>{
    
        lateinit var actionListener: CardActionListener
    
        abstract fun onCreateViewHolder(parent: ViewGroup): T
    
        abstract fun onBindViewHolder(holder:T, card: Card, position: Int)
    }
    which will be extended to do inflationa and other formalities to display data,
    class NewCardDelegate:CardViewHolder<NewHolder>{
    	//Rest of code
    }
    the reason I was doing this so that I could define a mutableMap<Int,CardHolder> and reduce the Adapter class
    val map =mutableMapOf<Int,CardHolder>
    map[25] = NewCard() //error
    but it seems like its not right way Please guide me for any other better way
    k
    p
    • 3
    • 4
  • i

    Ifvwm

    06/24/2019, 5:21 AM
    “”” open class Base(p:Int) class Derived(p:Int): Base(p) “””
    a
    • 2
    • 1
  • i

    Ifvwm

    06/24/2019, 5:21 AM
    why this derived class have p?
    d
    a
    • 3
    • 2
  • s

    scottiedog45

    06/24/2019, 6:05 PM
    Is this function “returning an object of type Dispatcher, but since Dispatcher is an abstract class I have to use the object keyword and declare that object as an instance of the abstract class?” 😐 not sure about this part:
    : Dispatcher = object : Dispatcher()
    fun updateErrorCodeForUrl(url: String, errorCode: Int) : Dispatcher = object : Dispatcher() {
            @Throws(InterruptedException::class)
            override fun dispatch(request: RecordedRequest): MockResponse {
                when (request.path) {
                    url -> return MockResponse()
                        .setResponseCode(errorCode)
                }
                return MockResponse().setResponseCode(422)
            }
        }
    s
    d
    • 3
    • 6
  • j

    JoshK

    06/24/2019, 11:55 PM
    Am I creating a race condition with the coroutines when I write
    val job = GlobalScope.launch { /* Things here */ }
    then
    job.invokeOnCompletion { /* It's done now */ }
    ? What's the best way to handle this?
    e
    • 2
    • 3
  • f

    Florian

    06/25/2019, 10:19 AM
    what parts of the project can REPL access? Only the functions?
    t
    • 2
    • 2
  • s

    spencerwi

    06/25/2019, 6:39 PM
    i.e. is there some way that Kotlin could be intelligent about automatic SAM conversion, without the need for extra boilerplate?
    s
    a
    • 3
    • 3
  • s

    scottiedog45

    06/25/2019, 8:43 PM
    I think this is a basic question, but why can I assign properties to data created with`val`?
    val intent = Intent(Intent.ACTION_VIEW)
    intent.data = Uri.parse(platform.appUrl)
    s
    e
    s
    • 4
    • 4
  • l

    lenqnr

    06/26/2019, 2:28 PM
    I have a rudimentary question.
    fun foo() {
        getData()?.let { data ->
            doSomething(data)
        }
    }
    Is it equivalent to this?
    fun foo() {
        val data = getData() ?: return
        doSomething(data)
    }
    I don't like adding more indentations, so came up with the second one. Is it OK?
    d
    a
    +2
    • 5
    • 13
  • c

    CamilleBC

    06/26/2019, 2:31 PM
    Hello ! I'm in need of advice. I'm trying to get a list of chapters from webfictions. When I'm sending a list of IDs (part of URL for retrofit to dl the chapter), it is an ordered list. I want to be able to download all chapters asynchronously (in case some download faster than others), but still keep the order from the first list (first in the chapterIds list will be the first in the return List<Chapter>, etc...). Is it the proper way to do this, or I'm going at it completely the wrong way?
    suspend fun getChapters(chapterIds: List<String>): List<Chapter> =
        mutableListOf<Chapter>().apply {
            chapterIds.forEach { launch { add(getChapter(it)) } }
        }
    
    suspend fun getChapter(chapterId: String): Chapter {
        val response = service.getChapter(chapterId)
        return if (response.isSuccessful) {
            val doc = Jsoup.parse(response.body()?.string())
            Chapter(
                doc.select(CHAPTER_TITLE_QUERY).text(),
                doc.select(CHAPTER_CONTENT_QUERY).html().lines()
           )
        } else Chapter()
    }
    d
    • 2
    • 7
  • s

    Sudhir Singh Khanger

    06/26/2019, 5:21 PM
    I have
    val articles: List<ArticlesItem?>? = null
    as part of my JSON response. I am trying to pull data off this list using
    articles[position]
    but Android Studio complains that
    Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type List<ArticlesItem?>?
    . Why can I do
    newsDataSet!![position]
    but not
    newsDataSet?[position]
    ?
    val articlesItem: ArticlesItem? = newsDataSet[position]
    full code https://github.com/sudhirkhanger/Samachar/blob/911f934252409e9a726e30a4865518e738042c93/app/src/main/java/com/sudhirkhanger/newsapp/ui/list/NewsListAdapter.kt#L45
    s
    p
    • 3
    • 3
  • n

    Nikita

    06/26/2019, 5:28 PM
    Hi! I have enum like this:
    enum class Events {
        "one",
        "two",
        "three"
    }
    And I need to get List<Map> like this:
    ({name: "one", id: "one"}, {name: "two", id: "two"}, {name: "three", id: "three"})
    Is there idiomatic way to do this? No ‘for’ loop.
    r
    r
    s
    • 4
    • 4
Powered by Linen
Title
n

Nikita

06/26/2019, 5:28 PM
Hi! I have enum like this:
enum class Events {
    "one",
    "two",
    "three"
}
And I need to get List<Map> like this:
({name: "one", id: "one"}, {name: "two", id: "two"}, {name: "three", id: "three"})
Is there idiomatic way to do this? No ‘for’ loop.
r

RoqueRueda

06/26/2019, 5:30 PM
i think you an use to: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/to.html
r

Ruckus

06/26/2019, 5:30 PM
Those aren't valid enum values...
👆 4
s

Shawn

06/26/2019, 5:33 PM
assuming this is what you really want, the code might look closer to this:
enum class Events {
    ONE,
    TWO,
    THREE,
}

val mappings = Events.values().map {
    mapOf("name" to it.name.toLowerCase(), "id" to it.name.toLowerCase())
}
n

Nikita

06/26/2019, 6:22 PM
Yep, I’m sorry about enum syntax. I wrote from memory. @Shawn Thank you! It’s work. I programmed a little in Python and such style are hard for me in Kotlin. I do not know what to do with it.
View count: 2