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
announcements
  • j

    Jukka Siivonen

    04/29/2020, 7:43 AM
    I'm trying to run JUnit tests with latest IDEA & updates and get
    Error:Kotlin: [Internal Error] java.lang.IllegalStateException: Backend Internal error: Exception during file facade code generation
    what to do? Other similar module works fine so I'm not sure what is wrong with this specific module which worked fine not so long ago
    • 1
    • 1
  • p

    Pypdeveloper

    04/29/2020, 7:50 AM
    Can anyone please tell me a free api so that I can collect the covid-19 information and plot it in a map, there location.
    a
    • 2
    • 11
  • a

    Ananiya

    04/29/2020, 9:37 AM
    i was trying to make kotlin covid console app from rapid api and they give me this code
    val client = OkHttpClient()
    val request = Request.Builder()
            .url("<https://covid-193.p.rapidapi.com/countries>").get()
            .addHeader("x-rapidapi-host", "<http://covid-193.p.rapidapi.com|covid-193.p.rapidapi.com>")
            .addHeader("x-rapidapi-key", "e9a2bc7b8amshcb0d6ea32047c46p129305jsnf42297251e7d")
            .build()
    val response = client.newCall(request).execute()
    then i run this code and give me this
    Response{protocol=http/1.1, code=200, message=OK, url=<https://covid-193.p.rapidapi.com/countries>}
    but all i want was to show me the countries and affected person number i download retrofit and gson but it look little bit harder how do i use it
    c
    z
    • 3
    • 3
  • c

    Chilli

    04/29/2020, 9:50 AM
    I got a problem with a Kotlin library with Gradle — building takes a pretty long time; e.g. “Starting Gradle Daemon...” message appeared after 2,5 minutes and starting took 50 seconds. I remember it used to be a lot faster a few days ago and I got no idea why. The full compilation took 4 minutes and 56 seconds, but I remember once Gradle didn't start even after 10 minutes. Also, there's some weird thing in the logs:
    > Task :compileKotlinMetadata
    Could not connect to Kotlin compile daemon
    Could not connect to kotlin daemon. Using fallback strategy.
    I have no idea why this happens
    t
    • 2
    • 2
  • m

    melatonina

    04/29/2020, 2:43 PM
    Hello. I'm not able to reference a method of the companion object of a sealed class as
    MySealedClass::method
    . I have to write explicitly
    MySealedClass.Companion::method
    . Is this normal?
    :yes: 1
    c
    • 2
    • 2
  • b

    bjonnh

    04/29/2020, 3:43 PM
    Is there a way to do a when directly on bytes? or do I always have to convert to Int?
    ✔️ 1
    c
    b
    • 3
    • 8
  • c

    Chilli

    04/29/2020, 4:00 PM
    Is it better to use require, assert and check functions or to just throw exceptions/errors myself?
    s
    • 2
    • 6
  • m

    manueldidonna

    04/29/2020, 5:27 PM
    I'm trying to understand how to add a JVM module to my android app project. I have a multi module project with a main app module and some kotlin library modules. - app - library1 - library2 Now I want to create a JVM desktop client reusing library1 and library 2. What can I do? I'm going crazy because I have a very superficial knowledge of how Gradle works
    m
    • 2
    • 1
  • p

    phldavies

    04/29/2020, 6:11 PM
    given
    data class Person(val name: String?, val age: Int?)
    is there any way to have
    inline val Person.isValid get() = name != null && age != null
    allow for smart-casting when accessing `name`/`age`?
    t
    r
    • 3
    • 4
  • b

    bjonnh

    04/29/2020, 6:53 PM
    I have a ByteBuffer reading a binary file with values as UInt32 . How do I read that in kotlin?
    s
    • 2
    • 7
  • s

    sannysanoff

    04/29/2020, 7:09 PM
    Hi, is there anything in Kotlin, which will allow me to alias Long, but in a way that it is not implicitly converted, so I never mix Long and my own type?
    s
    d
    • 3
    • 12
  • p

    Paul N

    04/30/2020, 9:22 AM
    A collections question: Say I have a list of Pairs, where first is a description, and second is a userid. How do I easily sort the list in the following order: a) all entries where second = "SYSTEM" ordered by description b) all entries where second = a particular value (e.g. the logged in user) c) all the remaining entries (second not SYSTEM or the logged in user) I don't think I can use a straight comparator as one of the values (the user) used for sorting is variable
    a
    d
    j
    • 4
    • 12
  • g

    Gopal S Akshintala

    04/30/2020, 11:03 AM
    What is the difference between a DSL and Util and API?
    🍿 3
    m
    • 2
    • 3
  • c

    colintheshots

    04/30/2020, 2:27 PM
    Quick style question... I'm doing a code review for a friend. For a const value, why might I prefer a top-level property vs. putting that same property inside a named object? I think the latter seems stylistically better in terms of code management, but I want to hear what others think.
    y
    s
    • 3
    • 2
  • c

    Chilli

    04/30/2020, 3:50 PM
    How to access data in the resources folder using Kotlin? Can I put any files I want to have access to in here or does it have some specific purpose? (I prefer if it's a common function, so I could do it on both JVM and Native)
    e
    • 2
    • 2
  • a

    Ananiya

    04/30/2020, 3:56 PM
    https://kotlinlang.slack.com/archives/C19FD9681/p1588261618220400
    j
    • 2
    • 1
  • e

    Ellen Spertus

    04/30/2020, 7:08 PM
    I am getting a build error message that I don’t understand:
    e: /Users/espertus/src/firefox-voice/android-app/app/src/main/java/mozilla/voice/assistant/intents/communication/ui/contact/ContactCursorAdapter.kt: (49, 30): Overload resolution ambiguity: 
    public final val itemView: View defined in mozilla.voice.assistant.intents.communication.ui.contact.MyAdapter.MyViewHolder
    public final val itemView: View defined in mozilla.voice.assistant.intents.communication.ui.contact.MyAdapter.MyViewHolder
    Lines 2 and 3 of the error are identical, so I don’t see the ambiguity. Here is the relevant code:
    class MyAdapter(
        private val cursor: Cursor
    ) : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
        class MyViewHolder(val itemView: View) : RecyclerView.ViewHolder(itemView) {
            private val ivContactPhoto: ImageView
    
            init {
                ivContactPhoto = itemView.findViewById(R.id.ivContactPhoto) as ImageView
            }
        }
    d
    d
    • 3
    • 5
  • j

    Jakub

    05/01/2020, 11:22 AM
    Silly question, but I believe, basic discipline like that adds up to cleaner code… I have data class that should be called
    List
    . How would you name that class?
    r
    d
    j
    • 4
    • 11
  • l

    LastExceed

    05/01/2020, 3:51 PM
    is there a fancy way to replace multiple consecutive whitespaces with single whitespaces ? or do i just repeatedly do
    .replace("  ", " ")
    until the string doesnt change?
    c
    c
    +3
    • 6
    • 8
  • m

    mathew murphy

    05/01/2020, 3:57 PM
    Should line numbers in exception backtraces correspond to actual linenumbers in Kotlin files? I ask because I'm getting a backtrace that doesn't seem to.
    j
    j
    k
    • 4
    • 5
  • m

    mathew murphy

    05/01/2020, 7:56 PM
    What might keep a Kotlin executable from exiting after main() has finished?
    a
    • 2
    • 1
  • s

    Sebastien Leclerc Lavallee

    05/01/2020, 9:18 PM
    Performance wise, what would be better? A list with function to fetch for a certain ID
    val listOfItems: List<Item> = listOf<Item>
    fun getItemWithId(id: String): Item {
      return listOfItems.filter { it.id == id }.first()
    }
    A map of Item per String
    val mapOfItems: Map<String,Item>
    Or any other solution I didn’t think of? Thanks 🙂
    m
    m
    +2
    • 5
    • 6
  • v

    viralshah

    05/02/2020, 12:42 AM
    Hi guys, I have a question which is driving me up the walls, how can I get yesterday EOD in a given time zone regardless of where my code is running (ie. JVM time). For example If I have a ZonedDateTime
    May 1 2020 5:35:00 PM PST
    I want to programatically get
    April 30 2020 11:59:59 PM PST
    I tried
    val currentTimeInTimeZone = ZonedDateTime.now(ZoneId.of(someTimeZone))
    
    val yesterday = ZonedDateTime.of(
                LocalDate.now().minusDays(1).atTime(LocalTime.MAX).truncatedTo(ChronoUnit.SECONDS),
                ZoneId.of(someTimeZone)
            )
    But it seems to work on my machine and when I push the code to production it does not return the correct value, any ideas / help would be appreciated
    p
    k
    t
    • 4
    • 5
  • j

    Jiri Bruchanov

    05/02/2020, 10:26 AM
    Hi guys, is there a way to have a secondary constructor with own (more specific) generic type ?
    s
    • 2
    • 2
  • i

    iex

    05/02/2020, 5:24 PM
    Is there a way to use
    T
    here to not having to pass
    clazz
    ? With reified parameter or something?
    fun <T> getObject(key: PreferencesKey, clazz: Class<T>): T? =
        getString(key)?.let {
            gson.fromJson(it, clazz)
        }
    t
    • 2
    • 3
  • i

    iex

    05/02/2020, 5:56 PM
    is there a more functional version of this typical "while loop with early exit"?
    fun foo(start: Foo): Result<List<MyRes>> {
        val list: MutableList<MyRes> = mutableListOf()
        var bar = start
        while (bar < condition) {
            when (val result = retrieveSomething(bar)) {
                is Success -> list.addAll(result.success)
                is Failure -> return Failure(Throwable("Error: ${result.error}"))
            }
            bar = bar.next()
        }
        return Success(list)
    }
    d
    s
    +2
    • 5
    • 23
  • m

    miha-x64

    05/02/2020, 7:47 PM
    What can I do with inline classes for Java interop? Currently I have methods returning useless
    Object
    or
    Object[]
    , and extensions with hyphen and hash, absolutely unusable from Java.
    l
    d
    • 3
    • 4
  • t

    Tmpod

    05/02/2020, 8:19 PM
    Hey! I was wondering if anyone knows about a Kotlin coroutine compatible Apache Cassandra wrapper, as I'd like to use Cassandra in my project. Thanks in advance 🙂
    d
    • 2
    • 1
  • j

    jeggy

    05/02/2020, 10:13 PM
    IntelliJ is giving me this warning. And I don't fully understand how to fix this. Could someone explain what I'm doing wrong by calling
    .get
    here?
    i
    n
    • 3
    • 6
  • s

    silvio

    05/03/2020, 8:19 AM
    Hey, quick question. When should we use the "it" keyword and when not? My google search on this was a little bit inconclusive.
    l
    d
    • 3
    • 12
Powered by Linen
Title
s

silvio

05/03/2020, 8:19 AM
Hey, quick question. When should we use the "it" keyword and when not? My google search on this was a little bit inconclusive.
l

LastExceed

05/03/2020, 8:48 AM
in the end it boils down to code style and readability. my rule of thumb is to use it when it's meaning becomes immediately obvious (usually in short lambdas such as
.forEach { println(it) }
) and avoid it in nested situations (since name shadowing is almost never a good thing). otherwise decide case by case. one could argue that for consistency you should just specify a name everywhere, but sometimes (especially in single-line scenarios) this will feel unnecessarily verbose
👍 2
s

silvio

05/03/2020, 9:33 AM
Alright, thanks! So it is not wrong to use it, because I read somewhere that there was discussion to remove it altogether, so I wasn't sure whether I can use it for small things like ResponseEntity.ok(it)
l

LastExceed

05/03/2020, 9:35 AM
the example you just gave could be both good or bad depending on the size and context of the lambda that creates
it
s

silvio

05/03/2020, 9:37 AM
it's for flux when I receive a Flux<DTO> from the service I return
dto.map { ResponseEntity.ok(it) }
l

LastExceed

05/03/2020, 9:38 AM
oh so that was the whole content of the lambda. yeah this is the kind of situation the
it
keyword exists for
d

David Eriksson

05/03/2020, 9:38 AM
@silvio:
dto.map(ResponseEntity::ok)
No
it
needed if the signature is compatible 🙂
s

silvio

05/03/2020, 9:40 AM
i tried that, but thats not working for me
I'd have to give a type argument for the Response entity and when I do that the ok cannot be resolved
d

David Eriksson

05/03/2020, 9:42 AM
Alright. But
it
is fine then.
s

silvio

05/03/2020, 9:42 AM
But thanks anyways 🙂
d

David Eriksson

05/03/2020, 9:43 AM
You could of course create a function "responseDto" with compatible signature
View count: 2