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

    Slackbot

    05/25/2021, 6:56 AM
    This message was deleted.
    g
    • 2
    • 1
  • r

    Rajkumar Singh

    05/25/2021, 11:04 AM
    I'm trying to build a
    List<List<Pacs>>
    from a large
    List<Pacs>
    . I created a function
    buildGroupedList
    that takes
    List<Pacs>
    as argument.
    r
    n
    • 3
    • 44
  • m

    mzgreen

    05/25/2021, 11:53 AM
    class Foo(val bar: Boolean)
    
    var foo: Foo? // initialized somewhere in the code
    
    fun test(): Boolean {
        return foo != null && !foo!!.bar // doesn't look nice
    }
    How can I make the expression in test() method nicer assuming I can't make foo non nullable?
    d
    e
    e
    • 4
    • 8
  • p

    Pablo

    05/25/2021, 12:50 PM
    If I have an interface as
    interface StringProvider {
      operator fun get(key: String): String
      fun getString(key: String): String
      ....
    }
    And I have a class that contains the key but can not add this
    StringProvider
    dependency how can I add this block to the constructor so I can get the key?
    class Foo {
      ....
      var age: String
      var weigh: String
      fun getExample(provider: (String) -> String) : Foo { 
        age = provider["ageprovider"]
        weigh = provider["weighprovider"]
      }
    }
    So in my class that I have a object of
    StringProvider
    I send just the
    StringProvider
    r
    • 2
    • 13
  • v

    Vijayakumar M

    05/25/2021, 1:47 PM
    Hi! Is it possible to collect the “StateFlow” in the same thread as producer? like in RxJava subjects? I’m trying to collect something using StateFlow but I’d like to do it in the producer thread. The collection execution code should block the producer if I do long running operations on the propagated value. The current implementation of flow forces us to use some kind of coroutine launchers for collection. Any help would be appreciated.
    c
    e
    • 3
    • 4
  • d

    dead.fish

    05/25/2021, 3:51 PM
    Hi all! Just for my sanity - am I seeing ghosts / am I doing something stupid or is this a real bug? https://youtrack.jetbrains.com/issue/KT-46947
    r
    e
    • 3
    • 5
  • i

    iamthevoid

    05/26/2021, 6:25 AM
    Hi everyone! Is there any wrapper for
    try { } catch (e: Exception) { }
    block that returns
    null
    on exception (in stdlib)? Something like
    runCatching { }
    , but without unwrapping.
    r
    d
    • 3
    • 3
  • n

    nisrulz

    05/26/2021, 11:50 AM
    Hi 👋 Which channel would be the best to ask about the
    @OptIn
    annotation. I am looking for an enhancement and would like to know if it even makes sense before opening an issue.
    c
    • 2
    • 1
  • c

    christophsturm

    05/26/2021, 12:44 PM
    why do fold and foldRight have their lambda parameters in a different order? (foldRight has acc first, and fold has it second)
    r
    • 2
    • 2
  • s

    spand

    05/26/2021, 1:09 PM
    How can I obtain a reference to a generic top level function? ie. something like this but working:
    fun <R> foo(block: () -> R): R = TODO()
    
    val fooName = ::foo.name
    e
    • 2
    • 2
  • r

    ribesg

    05/26/2021, 1:49 PM
    What do you prefer and why? 1️⃣
    nullableBoolean == true
    2️⃣
    nullableBoolean ?: false
    1️⃣ 20
    ⚖️ 1
    2️⃣ 2
    3️⃣ 1
    l
    i
    +4
    • 7
    • 36
  • u

    user

    05/26/2021, 3:42 PM
    message has been deleted
    👍🏽 1
    👍🏼 1
    👍 6
    t
    e
    a
    • 3
    • 5
  • e

    E.Kisaragi

    05/26/2021, 5:48 PM
    is there release note of each version?
    c
    t
    • 3
    • 3
  • r

    rnett

    05/26/2021, 7:51 PM
    I keep seeing things about Kotlin compatibility with jspecify, which looks great. I'd like to use it, but the jspecify repo says it's WIP and I can't find any published builds. Where are you/where should I get the artifacts from?
    e
    • 2
    • 1
  • m

    Mjahangiry75

    05/27/2021, 7:56 AM
    how can I use
    implementation project(":module")
    in kotlin build script
    c
    j
    +3
    • 6
    • 30
  • p

    Pablo

    05/27/2021, 8:13 AM
    How do I change this List<T>?
    data class Foo (val id: String, val name: String)
    val fooList = listof<Foo>(Foo("1","foo1"),Foo("2","foo22)
    Imagine I get this
    fooList
    as a parameter and I want to update this list, do I need to do a
    clone
    of the list and then a
    copy
    of the
    data class
    and update there the values?
    g
    a
    • 3
    • 11
  • p

    Paul Woitaschek

    05/27/2021, 8:36 AM
    Can somebody explain, why
    (0F/0F).coerceIn(0F,1F)
    NaN
    ?
    z
    s
    g
    • 4
    • 13
  • d

    Denys

    05/27/2021, 2:46 PM
    Help me please. I am trying to update kotlin plugin to version “1.5.10” from “1.4.32" and kotlinx-serialization-json to version “1.2.0” . After the update, the project stopped building - “java.util.NoSuchElementException: Collection contains no element matching the predicate. at org.jetbrains.kotlinx.serialization.compiler.backend.ir.IrBuilderExtension$DefaultImpls.serializableSyntheticConstructor(GeneratorHelpers.kt:1255)”
    g
    p
    t
    • 4
    • 11
  • k

    kschlesselmann

    05/27/2021, 4:00 PM
    Hi! I'm trying to benchmark a possible extension for https://github.com/MicroUtils/kotlin-logging. This lib provides ideomatic logging like
    <http://logger.info|logger.info> { "Some expensive $string" }
    . Now there's structured logging as well with https://github.com/logstash/logstash-logback-encoder. It would be great if I could use the lazy evaluated logging approach with multiple arguments as well. I came up with something like
    private fun KLogger.infoWithVarargSupplier(
            vararg arguments: () -> Any,
            message: () -> String,
        ) {
            if (isInfoEnabled) {
                info(
                    message.invoke(),
                    *arguments
                        .map { it.invoke() }
                        .toTypedArray(),
                )
            }
        }
    and now I'd like if there would be any huge performance impact in using a function like this. I tried creating a JMH benchmark but the results look suspicious … any suggestions?
    b
    o
    • 3
    • 20
  • w

    William Smyth

    05/27/2021, 5:07 PM
    Hey All, silly newbie question here:
    Would Kotlin be a good choice for developing an app that is essentially performing calculator and timer functions against data entries and automatic updates? ## App Basics • Mobile App: (IOS & Android, preferably) •
    v1
     isn't expected to be much more than form pages for manual data entry and then a fairly simple algorithm against said data to produce a suggested number based on the input. During these events it will also kick off a timer to track the time since the input for later calculations. My 
    v1
     architecture will likely be locally stored data (haven't decided on database type), which can be copied/saved to cloud storage providers (e.g., Google Drive, Box, OneDrive, etc.). The data needs to be encrypted for privacy. I'd like to collect anonymous usage statistics with zero private information and have that sent back to a web service that I intend to write—haven't decided on an event queue/bus service yet but will likely use something opensource initially. I ask because I believe a more native language would probably perform faster calculations and more reliable timers. Which is something I believe will become very important with later feature releases that are using more algorithms, and potentially AI/ML. (edited)
    b
    n
    c
    • 4
    • 5
  • d

    Daniel

    05/27/2021, 5:39 PM
    Is there a better way to have a Deferred<T> where the value is provided through a function call? I'm pretty sure this has a race condition with the exception that tells you the newMap you provided was never going to be used.
    class MapboxState constructor(override val coroutineContext: CoroutineContext): CoroutineScope {
        private val mapChan = Channel<MapboxMap>(1)
        val map = async {
            mapChan.receive()
        }
    
        internal suspend fun registerMap(newMap: MapboxMap) {
            if (map.isCompleted) {
                throw IllegalStateException("MapState already registered to a MapboxMap")
            }
            mapChan.send(newMap)
        }
    }
    d
    • 2
    • 2
  • s

    Slackbot

    05/27/2021, 8:21 PM
    This message was deleted.
    n
    c
    • 3
    • 11
  • s

    Simon Kågedal Reimer

    05/27/2021, 8:33 PM
    Hello! When bumping a project from Kotlin 1.3.60 to 1.5.10, the compiler seems to be erroring out with a java.lang.OutOfMemoryError. What can I do to analyze this further?
    r
    • 2
    • 10
  • p

    Paul Griffith

    05/27/2021, 10:58 PM
    Is there a way to (locally) decorate an operator fun to take precedence over a builtin on the class? I'm writing test cases where overloading
    get
    makes sense, but some of the data I have to pass in are arrays. I can manually 'up' cast to Any, but I'm curious if there's any other possibility.
    n
    e
    y
    • 4
    • 9
  • m

    mario

    05/28/2021, 6:46 AM
    Hi, Has anyone encountered problems in the tests to cover lambdas in sonarqube? There are always cases without covering
    e
    • 2
    • 3
  • m

    Michael Böiers

    05/28/2021, 12:44 PM
    Just ran across this, which throws an `UnsupportedOperationException`:
    val list = listOf(1, 2)
    if (list is MutableList) list.add(3)
    https://pl.kotl.in/_jfhJy6is Why is that? I mean, I get that the list is immutable, but why then can it be cast to MutableList?
    h
    • 2
    • 2
  • a

    Atchay Varma

    05/28/2021, 1:18 PM
    Hi guys I have made a Developer tool. Which is a search engine you can. There are 25+ Docs supported including Android, Flutter, React Native. For more info visit: https://www.producthunt.com/posts/devhuntr
    s
    • 2
    • 3
  • z

    zain

    05/28/2021, 2:44 PM
    I'm using something like this
    backButton.setOnLongClickListener {
        GlobalScope.launch(Dispatchers.Main) {
            if (backButton.isPressed) {
                viewPager.setCurrentItem(viewPager.currentItem - 1, true)
                delay(500)
            }
        }
        true
    }
    g
    d
    • 3
    • 34
  • z

    zain

    05/28/2021, 3:35 PM
    Created a Question on stack overflow with a better description, https://stackoverflow.com/q/67741723/4083142
    c
    • 2
    • 4
  • t

    Todd

    05/28/2021, 5:12 PM
    Is there any way to access the calling Class’ KClass object from an inline function? I think I’ve seen people abstract it from an empty lambda before, but I wanted to see if it was possible without this. It would be nice to not have to specific the exact type through a reified type parameter or
    this::class
    using a normal parameter.
    c
    • 2
    • 2
Powered by Linen
Title
t

Todd

05/28/2021, 5:12 PM
Is there any way to access the calling Class’ KClass object from an inline function? I think I’ve seen people abstract it from an empty lambda before, but I wanted to see if it was possible without this. It would be nice to not have to specific the exact type through a reified type parameter or
this::class
using a normal parameter.
c

Casey Brooks

05/28/2021, 6:27 PM
In general, no, you’d have to do some kind of manual setup to cleanly get the calling class’s type, but using a reified type parameter of the inline function’s receiver makes it fairly transparent to the caller https://pl.kotl.in/FtzdLAaBZ. Apart from that, you’d basically have to step through the stackframes to determine the caller, but that only comes back as a String and is a bit of a hack. But I’ve got an example ehre of doing exactly that to infer a tag for a library I maintain https://github.com/copper-leaf/clog/blob/master/clog-core/src/jvmMain/kotlin/clog/impl/InferredTagFinder.kt
t

Todd

05/28/2021, 7:49 PM
Ahh darn. The place I want to use it is already an extension function. But that’s very interesting to see the different implementations you’ve come up with. Thanks for sharing those snippets! It’s interesting because it seems like in the bytecode you would have access to the caller class, but I get that it probably takes a lot of work to integrate something like that into the language not to mention multiplatform.
View count: 2