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

    althaf

    10/11/2021, 8:57 AM
    Hi, i'm entering deadlock when setting value with lock inside a class property
    class CurrentServerTimestamp {
        private val lock: ReentrantLock = ReentrantLock()
    
        private var timestampInMillis: Long
            get() = lock.withLock { timestampInMillis }
            set(value) {
                lock.withLock { timestampInMillis = value }
            }
    
        init {
            timestampInMillis = CURRENT_SERVER_TIME_NOT_SET
        }
    
        companion object {
    
            private val instance = CurrentServerTimestamp()
    
            fun isValidTimeStamp(): Boolean {
                return instance.timestampInMillis != CURRENT_SERVER_TIME_NOT_SET
            }
    
            fun get(): Long = instance.timestampInMillis
    
            fun set(currentServerTimestamp: Long) {
                instance.timestampInMillis = currentServerTimestamp
            }
        }
    }
    set(value) {
                lock.withLock { timestampInMillis = value }
            }
    I think this is causing the dead lock, is there any way to over come this and still i get the intended behavior ?
    e
    • 2
    • 4
  • c

    Colm Murphy

    10/11/2021, 11:14 AM
    I just discovered that the Byte and Short classes (and their unsigned counterparts) have no 
    shl
     or 
    shr
     infix functions. Is this intentional or not?
    e
    c
    • 3
    • 4
  • c

    Carl Bateman

    10/11/2021, 2:57 PM
    How do I load a bitmap (or jpg or png) from file (not URL)?
    p
    • 2
    • 3
  • m

    Muhammad Usama

    10/11/2021, 5:22 PM
    hello folks.. can someone invite me to the composable channel..??
    v
    k
    • 3
    • 2
  • b

    blue

    10/11/2021, 10:30 PM
    Hi folks, I’m playing with elvis(?:) operator and looking for some help, I want to return from the method when my object is null but before returning from the method I want to add a log statements, what is the correct way of doing that?
    val record = (repository.findById(id) ?: (<http://log.info|log.info>("log message here") return))
    😬 1
    p
    r
    +4
    • 7
    • 8
  • b

    Brad Harris

    10/11/2021, 11:27 PM
    What is the difference between file level: val myVariable = “const” const val myVariable = “const”
    j
    e
    +2
    • 5
    • 9
  • j

    Jérémy CROS

    10/12/2021, 3:31 PM
    Hey guys 🙂 Was looking to do something like that but it doesn’t seem to be allowed
    data class Foo(val a:Int, val b = 0)
    val bar = Foo(a = 3, if(param) b = 5 /*else keep the default param */)
    Is there an alternative other than
    val bar = if(param) Foo(...) else Foo(...)
    🇳🇴 3
    h
    c
    +4
    • 7
    • 13
  • m

    missguru

    10/12/2021, 3:43 PM
    Hey folks, Can someone please recommend a good Android repository that showcases coroutine and flow implementations with tests?
    m
    • 2
    • 1
  • s

    Shabinder Singh

    10/12/2021, 6:08 PM
    Where can I ask somewhat off-topic thing which is not related to Kotlin Directly, Which channel is suitable for this? , as this community is quite large and I guess some people may even be happy to help/answer my query...
    r
    • 2
    • 2
  • k

    Karlo Lozovina

    10/12/2021, 8:46 PM
    is there a way to choose what concrete type
    associateWith
    returns?
    🇳🇴 1
    h
    e
    • 3
    • 4
  • a

    ankushg

    10/13/2021, 12:50 AM
    Helping an iOS coworker get ramped up into our KMP codebase. Overall things are looking great, but they mentioned that they don't quite get the point of the Kotlin StdLib Collection functional operators (map/filter/associate/etc) vs a more "standard” mutable collection + iteration I'm gonna be honest — I've been working in Kotlin for quite a while and those list operators just come naturally to me. At the same time, I don't think “because they're more idiomatic and look better (to me)” is a good enough reason. I know there are also benefits like Sequence-compatibility and ease of extracting narrowly scoped helper methods, but I'm sure there's many other reasons to use them (and situations where you shouldn't use them) that I've internalized but can't easily recall and articulate Does have a link to a good post that details the pros/cons of those operators vs the “not-kotliny” approach?
    j
    m
    +3
    • 6
    • 7
  • m

    Manuel Dossinger

    10/13/2021, 7:54 PM
    Hey. I can do `my?.chained?.call?.of?.operators?`and get null, if any of these is null. Is there a nice way of achieving the same for parameters? e.g.
    fun foo(a: Type1, b: Type2, c: Type3): Type4
    
    val result: Type4? = foo(myA?, myB?, myC?) // is null if any of the parameters is null
    g
    e
    +2
    • 5
    • 12
  • m

    Mihai Voicescu

    10/14/2021, 10:11 AM
    I need to serialize a data class I do not own. It just needs the default Serializer. Is there any easy way of doing this (hopefully without defining a custom serializer)?
    ✅ 1
    • 1
    • 1
  • d

    dave08

    10/14/2021, 11:36 AM
    If I have:
    sealed interface Foo
    
    object Bar : Foo
    
    object Baz : Foo
    
    fun <T : Foo> getFooObjects(): List<T> = TODO("How do I get this list?")
    m
    • 2
    • 6
  • e

    egek

    10/14/2021, 1:45 PM
    I want to call a method that makes an API call which is triggered by user interaction but I want to prevent it to get called multiple times if it hasn't been 1 minute yet, what would be the best way to do this?
    k
    g
    • 3
    • 2
  • p

    Peterpaul Klein Haneveld

    10/15/2021, 8:03 AM
    I'm working on a Kotlin compiler plugin using arrow-meta. I'd like to know what's the official way to report compilation errors and warnings. And is there a way to have intellij handle these errors and warnings and display them?
    e
    • 2
    • 2
  • a

    Ayfri

    10/15/2021, 2:04 PM
    Hi, is there any class or functions to print in color in std kotlin ?
    🇳🇴 1
    j
    g
    • 3
    • 2
  • m

    Mihai Voicescu

    10/15/2021, 3:59 PM
    What library would you recommend for checked exceptions? https://arrow-kt.io/docs/apidocs/arrow-core/arrow.core/-either/ or https://github.com/michaelbull/kotlin-result (or maybe others)
    ✅ 1
    v
    j
    +2
    • 5
    • 10
  • j

    Jakub Aniola

    10/17/2021, 12:37 PM
    Why use MutableList<T> instead of ArrayList<T> in Kotlin? What was the idea standing behind the creation of that class in Kotlin when mostly the rest of the collections are used as declared in Java? If you have any docs/articles that might help me understand it, it would be very helpful. Thanks 👋🏼
    r
    i
    k
    • 4
    • 5
  • s

    Stylianos Gakis

    10/17/2021, 4:22 PM
    With `@JvmInline value class`es existing, I’ve been wondering, is there any reason why you would explicitly not want any class you have that happens to have a single value in it’s constructor to be a
    value class
    ? Like I see the benefits of it, but if I am creating a new data class with 1 parameter anyway, why would I not just make it a value class? Any gotchas? Couldn’t find anything in the KEEP regarding this.
    s
    e
    d
    • 4
    • 5
  • v

    Vitali Plagov

    10/18/2021, 8:24 AM
    I have a data class like
    data class ProfileItem(val id: String, val item: Item)
    data class Item (val code: String)
    When I get a
    List<ProfileItem>
    from the 3rd service (can’t control it), the
    item
    field for some elements in the list might be
    null
    . And when I do
    val eligibleCodes = service.gerProfileItems().filter { it.item.code in approvedCodes }
    it fails with NPE, so I had to do
    filter { it.item != null }
    once I got the list. And IntelliJ complains about this filtering saying that this condition is always true. Is it an issue with the IntelliJ IDEA’s inspection? Or I should do this operation differently?
    j
    t
    s
    • 4
    • 4
  • c

    conner

    10/18/2021, 7:00 PM
    is it an anti-pattern to use sealed classes/interfaces as an approximation of an algebraic data type? i've been doing things like below, but it seems that this causes
    instanceof
    checks -- so naturally various stack overflow answers mentioned "code smell", and i'm wondering if there's truth to that 🙂
    sealed class Node
    
    data class Leaf(x: Int): Node()
    data class Tree(left: Node, right: Node?): Node()
    a
    d
    s
    • 4
    • 5
  • a

    Alejo

    10/19/2021, 1:24 PM
    Hello everyone! I would want to know what options do I have if I want something like a Min/Max Heap or Priority Queue in Kotlin. I look in the docs but didn't find anything 😞
    a
    • 2
    • 2
  • m

    Mihai Voicescu

    10/19/2021, 3:04 PM
    Sealed interface serialisation seem to be broken unless explicitly registered. Am I missing something?
    import kotlinx.serialization.*
    import kotlinx.serialization.json.Json
    import kotlin.test.Test
    
    sealed interface iFoo {
        @Serializable
        @SerialName("a")
        class A() : iFoo//Foo(),
    }
    
    class EventTest {
        @Test
        fun testKotlinLang() {
    //        // this works
    //        val json = Json { serializersModule = SerializersModule {
    //                polymorphic(iFoo::class) {
    //                    subclass(iFoo.A::class, iFoo.A.serializer())
    //                } } }
    
            val json = Json
    
            val a = iFoo.A() as iFoo
            val s = json.encodeToString(a)
            val a1: iFoo = json.decodeFromString(s)
        }
    }
    ✅ 1
    p
    • 2
    • 2
  • i

    Itamar F. Lima

    10/19/2021, 6:10 PM
    Guys I am new at Kotlin, can you guys tell me where I am getting wrong?
    a
    • 2
    • 4
  • k

    Karlo Lozovina

    10/19/2021, 8:59 PM
    Given an expression
    someCollection.take(42).forEach { /* ... */ }
    is there a way to access the collection inside the forEach that the forEach is iterating over?
    d
    m
    j
    • 4
    • 11
  • m

    Michael Langford

    10/19/2021, 9:30 PM
    Data modeling question: I'm trying to essentially model 5 different csv files that have a few common fields as Kotlin objects that are going to be displayed and edited in lists. So like page 1 would be identifier, time, last_update, location name, color. Page 2 would be identifier, time, last_update, activity_type, length, etc, with all of them having identifier, time, and last_update in common. In my Android app's UI, these will all be displayed in a list, by time. Is there a gotcha that makes sealed classes a bad move for this data modeling situation?
    d
    • 2
    • 5
  • b

    blue

    10/19/2021, 11:51 PM
    Hi👋, Can someone tell me why the compile error is going away as soon as uncomment the
    student as Student
    from the below code? Don’t I have to explicitly assign the cast result to a variable to access the
    score
    property?
    abstract class Person(val name: String)
    class Student(val score: Int, name: String) : Person(name)
    class Teacher(name: String) : Person(name)
    
    fun someFun(student: Person) {
    //  student as Student
        
        println(student.score)
    }
    j
    • 2
    • 6
  • n

    nilTheDev

    10/21/2021, 8:03 AM
    Isn't there any plan to replace Gradle? If you want reasons just Google it.
    g
    j
    +5
    • 8
    • 18
  • b

    Bert Heyman

    10/21/2021, 9:36 AM
    TL;DR: how can I install Exposed in Ktor?
    d
    • 2
    • 2
Powered by Linen
Title
b

Bert Heyman

10/21/2021, 9:36 AM
TL;DR: how can I install Exposed in Ktor?
d

Damian Zawadzki

10/21/2021, 9:38 AM
maybe try on #ktor or #exposed
b

Bert Heyman

10/21/2021, 9:39 AM
Will do! Thanks
View count: 4