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

    Marko Kovacevic

    11/15/2020, 4:14 PM
    [Kotlin HTTP client] - Any recommendations for a client library? Mainly require for trying out concurrency locally in a sandbox environment console app. Noticed Ktor client, but there's no documentation as it's in progress.
    a
    • 2
    • 1
  • w

    Will Nixon

    11/15/2020, 9:03 PM
    Hi all, getting a little confused about an issue I’m having. Have implemented a Google Oauth process to connected to a user’s drive. Locally, in an emulator, everything works fine, but as soon as I try to test the app in Internal Testing/Closed Testing, the app crashes with this error:
    java.lang.RuntimeException: 
      at android.os.AsyncTask$4.done (AsyncTask.java:415)
      at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:383)
      at java.util.concurrent.FutureTask.setException (FutureTask.java:252)
      at java.util.concurrent.FutureTask.run (FutureTask.java:271)
      at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:305)
      at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
      at java.lang.Thread.run (Thread.java:923)
    Caused by: java.lang.IllegalArgumentException: 
      at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument (Preconditions.java:5)
      at com.google.api.client.util.Preconditions.checkArgument (Preconditions.java:10)
      at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.getDetails (GoogleClientSecrets.java:10)
      at com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow$Builder.<init> (GoogleAuthorizationCodeFlow.java:10)
      at com.jenix.lemmi.ui.splashscreen.SplashScreenActivity.getCredentials (SplashScreenActivity.java:10)
      at com.jenix.lemmi.ui.splashscreen.SplashScreenActivity.access$getCredentials (SplashScreenActivity.java:10)
      at com.jenix.lemmi.ui.splashscreen.SplashScreenActivity$AsyncGetCredentials.doInBackground (SplashScreenActivity.java:10)
      at com.jenix.lemmi.ui.splashscreen.SplashScreenActivity$AsyncGetCredentials.doInBackground (SplashScreenActivity.java:10)
      at android.os.AsyncTask$3.call (AsyncTask.java:394)
      at java.util.concurrent.FutureTask.run (FutureTask.java:266)
      at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:305)
      at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)
      at java.lang.Thread.run (Thread.java:923)
    From my understanding, it’s possibly due to Oauth credentials not matching - I’m using the SHA-1 signing key from the Play Console, so not sure what else i’m missing, Any ideas?
    u
    • 2
    • 1
  • c

    coder

    11/16/2020, 8:38 AM
    Hi, Do i need to learn java before i start learning kotlin?
    o
    • 2
    • 3
  • s

    speed_star

    11/17/2020, 8:33 AM
    Hi. I'd like to check whether
    null
    property is exists in data class. Should I check for each property like as below? Or there is other good way?
    data class Book(val name: String?, val author: String?, val price: Int?)
    
    fun isExistNull(): Boolean {
        if (name == null || author == null || price == null) {
            return true
        }
        return false
    }
    j
    n
    • 3
    • 2
  • w

    waltermcq

    11/18/2020, 7:18 PM
    I'm trying to do a Kafka tutorial in Kotlin and wondered what the following code is in idiomatic Kotlin
    // send data - asynchronous
                producer.send(record, new Callback() {
                    public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                        // executes every time a record is successfully sent or an exception is thrown
                        if (e == null) {
                            // the record was successfully sent
                            <http://logger.info|logger.info>("Received new metadata. \n" +
                                    "Topic:" + recordMetadata.topic() + "\n" +
                                    "Partition: " + recordMetadata.partition() + "\n" +
                                    "Offset: " + recordMetadata.offset() + "\n" +
                                    "Timestamp: " + recordMetadata.timestamp());
                        } else {
                            logger.error("Error while producing", e);
                        }
                    }
                });
            }
    a
    • 2
    • 11
  • o

    oday

    11/19/2020, 9:06 AM
    I know that val cannot be reassigned, but how would I for example send a variable to a function to do something with it?
    private fun resetCounterAndGame(counter: Int) {
        if (counter == 2) {
            gameButtonText.set(resProvider.getString(R.string.try_another_number))
            gameStarted = false
            counter = 0 <--- val cannot be reassigned of course
        }
    }
    w
    v
    +3
    • 6
    • 19
  • i

    Ifvwm

    11/20/2020, 3:28 AM
    what classA.instance means? equal to classA()?
    v
    • 2
    • 1
  • m

    Mohamed Daif

    11/21/2020, 2:06 PM
    Hi, All. I am learning Kotlin by hyperskill.org JetBrain Academy I getting this error when checking my solution but when running it in IDE it's working fine https://hyperskill.org/projects/83/stages/458/implement is this issue can be fixed by me or only by hyperskill JetBrain Academy The compile configuration has been deprecated for dependency declaration. This will fail with an error in Gradle 7.0. Please use the implementation configuration instead. Consult the upgrading guide for further information: https://docs.gradle.org/6.6.1/userguide/upgrading_version_5.html#dependencies_should_no_longer_be_declared_using_the_compile_and_runtime_configurations at build_bzr9s6nt7rztzjinzwhqs1atm$_run_closure1$_closure4.doCall(/mnt/sdb1/IntelliJIDEAProjects/Flashcards/build.gradle:23) (Run with --stacktrace to get the full stack trace of this deprecation warning.)
    v
    • 2
    • 2
  • m

    Marko Kovacevic

    11/21/2020, 8:34 PM
    [CompletableFuture] I’m having issues converting CompletableFuture to a suspendable function as there aren’t any examples nor guides for it. Does someone know what is the proper way to handle this? I’m using the Java 11 Http client and creating a wrapper for calling an API.
    suspend fun HackerNewsApi.fetchItem(id: Int): CompletableFuture<HttpResponse<String>> {
        return client.sendAsync(
            request("${this.domain}/v0/item/$id.json"),
            HttpResponse.BodyHandlers.ofString()
        )
    }
    n
    d
    • 3
    • 2
  • c

    Colton Idle

    11/22/2020, 2:59 AM
    I'm reading effective java and at some point it mentions WeakReferences which got me to searching if it exists in Kotlin as well. I've been using kotlin for about 2 years, but never had a need to use it. Is
    WeakReference
    something that's popular? Should I be using it in some typical situations of development? I understand that I won't be using the entire std-lib, but references are everywhere and so it seems like I should have come across a valid use of WeakReference by now (I mostly build android apps if it helps)
    z
    • 2
    • 1
  • u

    ursus

    11/22/2020, 3:10 AM
    How do I search a top level function in intellij?
    g
    • 2
    • 2
  • p

    poohbar

    11/22/2020, 4:00 PM
    Is there a shorthand for:
    (0..10).map { random.nextDouble() }
    ? Basically, I am looking for
    repeat(n)
    where the function can return a value:
    newRepeat(10).map { random.nextDouble() }
    i
    • 2
    • 2
  • c

    Colton Idle

    11/23/2020, 1:41 AM
    All classes in java extend Object. All classes in Kotlin extend Any. Why is that?
    n
    r
    s
    • 4
    • 7
  • n

    Nikhil

    11/23/2020, 3:58 AM
    What's the basic difference between Flow and Live data? Can anyone explain this with an example
    j
    s
    • 3
    • 3
  • r

    Ruckus

    11/23/2020, 4:22 AM
    message has been deleted
    m
    • 2
    • 2
  • w

    WildOne (Yuri)

    11/23/2020, 9:12 AM
    For example, how do I refer to other objects in the View by ID/CSS selector?
    s
    i
    r
    • 4
    • 4
  • m

    Mateusz Holak

    11/23/2020, 3:55 PM
    Hi. I have some troubles to do some transformations like extension of LiveData has one
    LiveData<X>.map {} => transform type MutableLiveData<DomanType> -> LiveData<UiType>
    I would like replace LiveData with StateFlow but i need to transform domain type to UI type that i have for each layers. Which one method i should use ? The same method "map" in Flow return Flow<R> but i need StateFlow<T>. I can also do transormation when i have data from useCase and then assign MutableStateFlow to StateFlow by invoking asStateFlow but its a little worse solution than i have with LiveData right now. Thanks for any advice. I found similar question here: https://github.com/Kotlin/kotlinx.coroutines/issues/2008
    a
    • 2
    • 12
  • n

    Nicolas Mariano Obregon

    11/24/2020, 3:33 PM
    <<SOLVED>> Hi everyone! I’m new to Kotlin and functional programming, coming from Java OO. Here’s my question: If I want to define some interface method implementations using
    runCatching
    , something like this below, how should I define my interface method signature in order to return whatever the runCatching returns? I hope I was clear enough. Thanks in advanced
    interface IMyInterface { 
        suspend fun myFunction()
    }
    
    class MyClass : IMyInterface {
        override suspend fun myFunction() = runCatching {
    
        }.onFailure { ... }.getOrThrow()
    }
    v
    s
    • 3
    • 8
  • a

    alex cole

    11/25/2020, 12:50 AM
    Hi, I am wanting to replicate a python feature
    def myFunction(a,b,c): 
        return lambda x: a * x ** 2 + b * x + c
    however I am not understanding what is wrong with
    fun potentialEnergy(charge1, charge2, k){
        val x = {position: Double -> k * charge1 * charge2 / position / position} // creating lambda function
        return x
    }
    What is wrong with this lambda function expression.
    ✅ 1
    m
    m
    n
    • 4
    • 6
  • u

    UnAn

    11/25/2020, 5:29 PM
    General question, what are the process of making in concrete the app? I have my documentation on what the app does, its functionalities and then? Do i start with the database? Then make the layout? Then logic? And then the "front-end"? What is the correct process?
    a
    t
    c
    • 4
    • 10
  • r

    ruwinmike

    11/27/2020, 10:48 AM
    If sealed class is internal, so I don’t have to write internal modifier to his heirs, or not?
    t
    t
    • 3
    • 2
  • m

    Maxime Recuerda

    11/28/2020, 5:25 PM
    Message moved in #kodein, sorry for the wrong channel!
    a
    • 2
    • 2
  • j

    Joshy Josh

    12/04/2020, 11:19 PM
    Is there a simple way to create a generic type-safe builder that can be used with a lambda? like
    functionName<ClassName> { …className functions}
    ? I know it can be done specifically, but I was wondering if there was a way to create a generic approach. in Kotlin.
    s
    • 2
    • 15
  • t

    Tony Blundell

    12/05/2020, 7:52 PM
    Could I get a quick code review please? Is the use of while-true and runBlocking OK here?
    class WsClient {
        private val url = "<http://example.com>"
        private val httpClient = HttpClient { install(WebSockets) }
    
        suspend fun start() {
            httpClient.wss(HttpMethod.Get, url) {
                send("Hello")
                while (true) {
                    when (val frame = incoming.receive()) {
                        is Frame.Text -> println(frame.readText())
                        is Frame.Binary -> println(frame.readBytes())
                    }
                }
            }
        }
    }
    
    fun main() = runBlocking {
        WsClient().start()
    }
    m
    • 2
    • 2
  • p

    poohbar

    12/06/2020, 4:19 PM
    Does it matter whether I extend
    Exception
    or
    RuntimeException
    in Kotlin? I thought it doesn't but my
    Exception
    extension is getting wrapped in
    UndeclaredThrowableException
    when interacting with a Java library.
    v
    t
    s
    • 4
    • 4
  • m

    Michael

    12/08/2020, 3:19 PM
    Hello, can anyone help with how I might handle timeouts/ errors when I try and connect to an offline database using the exposed framework > Database.connect
    👀 1
    s
    a
    • 3
    • 2
  • a

    Andrea Giuliano

    12/09/2020, 1:06 PM
    hi guys, I have a performance question to ask. I’m working with IntArray (for efficiency) but then at some point I want to convert that to a list. I can use
    .toList()
    method no problem but then when I check for efficiency the blame graph tells me that tolist() is not that efficient. Anything I’m missing? Any suggestion?
    n
    a
    +4
    • 7
    • 11
  • d

    Daniele B

    12/09/2020, 7:20 PM
    Android Studio is giving me a warning that I should use Java 11. I have installed it here: /Library/Java/JavaVirtualMachines/jdk-11.0.9.jdk Can you please explain how I can configure Android Studio (or my app) to use it?
    a
    • 2
    • 6
  • s

    Steven Wang

    12/09/2020, 8:40 PM
    What is the kotlin way to handle thread safety/concurrency? (instead of using synchronized like Java) I am thinking to create a top-level object by call newSingleThreadContext() and pass it around to make sure the operation to change given object all come from same thread. Is this usually how we do in Kotlin?
    r
    • 2
    • 1
  • m

    mickeelm

    12/12/2020, 11:54 AM
    I'm scratching my head here a bit regarding extension functions. Can someone explain to me why this works
    private fun <String> HashMap<String, String>.myExt(key: String, incomingValue: String) {
        this[key] = incomingValue
    }
    But not this
    private fun <String> HashMap<String, String>.myExt(key: String, incomingValue: String) {
        this[key] = "something else"
    }
    The latter gives me (in IntelliJ):
    Type mismatch.
    Required: String#1 (type parameter of myExt)
    Found: kotlin.String
    j
    m
    +2
    • 5
    • 16
Powered by Linen
Title
m

mickeelm

12/12/2020, 11:54 AM
I'm scratching my head here a bit regarding extension functions. Can someone explain to me why this works
private fun <String> HashMap<String, String>.myExt(key: String, incomingValue: String) {
    this[key] = incomingValue
}
But not this
private fun <String> HashMap<String, String>.myExt(key: String, incomingValue: String) {
    this[key] = "something else"
}
The latter gives me (in IntelliJ):
Type mismatch.
Required: String#1 (type parameter of myExt)
Found: kotlin.String
j

Joris PZ

12/12/2020, 11:58 AM
Interestingly,
this[key] = "something else" as String
fixes the compiler error?
Ah it changes it to a warning about an unchecked cast. Somehow the type of the value in the Map is inferred to be
String#1
? Seems like a bug
m

mickeelm

12/12/2020, 12:03 PM
Exactly, was just going to write that. So you think it's a bug? I was assuming that I'm missing something
j

Joris PZ

12/12/2020, 12:04 PM
Ah no, wait! It should be
fun HashMap<String, String>.myExt(key: String, incomingValue: String) {
    this[key] = "something else"
}
The initial
<String>
makes no sense here
Hold on, does it somehow use
String
as a generic type parameter instead of
kotlin.String
?
m

mickeelm

12/12/2020, 12:05 PM
Of course! Thank you very much 🙂 It was autogenerated but that makes sense.
j

Joris PZ

12/12/2020, 12:05 PM
You're welcome 🙂
m

mickeelm

12/12/2020, 12:05 PM
Regarding
String
vs
kotlin.String
I don't know really
m

Milan Hruban

12/12/2020, 1:27 PM
the
String
in the original function is just a name you have given to the generic parameter, it has nothing to do with
kotlin.String
. You could replace it with
Abcd
(or more often used
T
) and the function would work exactly same
➕ 1
m

mickeelm

12/12/2020, 1:31 PM
Now that you mention it, it's very clear 😃 thank you! 😃
👋 1
j

Joris PZ

12/12/2020, 2:15 PM
It surprises me that that is even allowed, the potential for confusion is profound 😀
😅 1
m

Milan Hruban

12/12/2020, 2:31 PM
how would you prevent it tho? Ban all possible classnames?
m

mickeelm

12/12/2020, 2:32 PM
Yeah I thought about that too, would be kind of tricky tro draw a line there
n

nanodeath

12/13/2020, 5:44 PM
this is a pretty funny issue 🙂 I dunno about banning classnames, but any generic parameter that's not a single character should catch your eye. (I don't love that convention but it's the convention...)
m

Matteo Mirk

12/14/2020, 11:31 AM
I saw code using type parameters longer than a letter, always adopted the Uppercase convention, to avoid confusion. Example:
Message<REQUEST, RESPONSE>
or in Assertj:
interface Assert<SELF extends Assert<SELF, ACTUAL>, ACTUAL> ...
View count: 23