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
getting-started
  • r

    Ryan Zidago

    01/14/2022, 5:46 PM
    How can I make a coroutine print to another one? If I do:
    fun someFunction() = runBlocking {
      greet()
    }
    
    suspend fun greet() = coroutineScope {
      launch {
        delay(1_000)
        println("world!")
      }
      println("hello")
    }
    I will see both "hello" and "world!" printed, but the code is blocked until
    greet
    is done. However if Iaunch
    greet
    inside a coroutine:
    fun someFunction() = runBlocking {
      launch {
        greet()
      }
    }
    
    suspend fun greet() = coroutineScope {
      launch {
        delay(1_000)
        println("world!")
      }
      println("hello")
    }
    the code is non blocking anymore but I can't see any messages printed to the console 🤔
    j
    • 2
    • 5
  • r

    Ryan Zidago

    01/15/2022, 4:55 PM
    Do you usally commit or ignore those files?
    .gradle/
    	.idea/
    	bin/
    	build/
    	gradle/
    	gradlew
    	gradlew.bat
    r
    a
    • 3
    • 8
  • l

    Lucas León

    01/15/2022, 6:40 PM
    Hi guys! So, I’m trying to create a GitHub Library with Kotlin, it’s still a very early work in progress (here’s the repo: https://github.com/lucasleon2107/KGitHub) but there’s still some thing I need to tackle and not sure/don’t know how to approach them, like: • I’m using Ktor Client for HTTP requests, and you can use different engines for different platform, how can I let the person who’s using the library pick the engine that is more convenient with Gradle? • Which tool should I use for auto bumping the version using semver? • How should I approach test? Should I just mock the api calls? Because in this case there are not much business rules to test • Which tools should I use for CI? Want to prevent code commits without being tested and enforce some code stylings maybe There are more things I’d like to solve but they are not in the top of my head right now but I will add them to the list when I remember then Please feel free to collaborate if you feel like it and I’d like to receive some feedback for this tiny proof of concept that I’m developing. Have a great day!
    h
    b
    • 3
    • 5
  • i

    Itish Srivastava

    01/16/2022, 5:08 PM
    I am searching for Kotlin Discord Link, I am learning stuff from JetBrains Academy and would like to know people who use Kotlin, in order to learn and grow. Thank you~
    m
    • 2
    • 4
  • a

    Ayfri

    01/16/2022, 7:48 PM
    Hi, I have a DateTimePeriod from an API, and I want to convert it to
    Clock.System.now()
    + the period as an Instant, how do I do this ?
    i
    • 2
    • 2
  • u

    umitems

    01/17/2022, 12:43 AM
    I create data class X (...) then I use X.toString and now I want to convert that string back to data class X object what shall I do? Is there a Kotlin way to done this?
    j
    e
    r
    • 4
    • 5
  • p

    Pavle Joksovic

    01/17/2022, 1:41 PM
    I have
    private val _toneMap = MutableStateFlow(hashMapOf(0 to listOf<Tone>()))
    and I update the value like this
    toneMap[index] = tones
    val toneMapCopy = HashMap(toneMap)
    _toneMap.value = toneMapCopy
    there is an issue when the toneMap[index] already contains a list, the value is not updated. Any idea how to fix this?
    h
    • 2
    • 2
  • j

    Jason5lee

    01/18/2022, 7:28 AM
    How to define a internal
    var
    property that only its
    get
    is
    PublishedApi
    ?
    j
    v
    • 3
    • 10
  • k

    Kebbin

    01/18/2022, 11:59 AM
    Hello! I can rotate an object on the screen using the mouse location and the
    atan2
    function. As soon as I begin the rotation, the object jumps to point at the mouse location (rotation angle follows mouse angle), but I want to be able to rotate the object relative to the mouse angle. I can measure the difference between the current rotation, and the mouse angle when the rotation begins, but I cant make the
    diff
    value remain constant during the rotation!
    I need to learn how you set a value once from other variables without it then constantly updating itself. Can someone show me how? Thanks!
    s
    • 2
    • 4
  • a

    acoconut

    01/19/2022, 2:58 PM
    Not sure where to ask this. We used to have kotlin 1.4 and use mapstruct and the @KotlinBuilder annotation everywhere. But with kotlin 1.6 @KotlinBuilder doesn’t work anymore. What have people done to solve this? It seems like I don’t need it for the mapstruct per se anymore, but I’m finding myself changing all lists to mutable lists. As if Kotlinbuilder used to be able to get it working with lists but without it everything needs to be actually mutablelists. Does this sound familiar to anybody?
    t
    r
    • 3
    • 4
  • m

    MarkRS

    01/19/2022, 4:06 PM
    How do I create a class to inherit from a class that can either take an instance of itself or nothing as an initialiser? I had assumed
    class childClass(child: childClass?) : parentClass(child) {
        constructor() : this( null)
    but this breaks when calling it as childClass(). The parent class I'm trying to inherit from is a Java class, "Path" from android.graphics, but I assume that doesn't matter. I've checked that code and it claims to accept a null.
    r
    e
    k
    • 4
    • 11
  • a

    Adam Firen

    01/20/2022, 2:51 PM
    hi guys, I am thinking about using kotlin dsl to configure my ci/cd pipelines. I have been looking for OOTB solutions and found only TeamCity one. Is anyone aware of any alternatives or initiatives to build one?
    p
    a
    • 3
    • 3
  • l

    Lokik Soni

    01/20/2022, 3:07 PM
    I have a question related to memory or app performance. Please suggest me which box of code 1 or 2 help me in less memory allocation or both will use same amount of memory. In first box I have used map and putting data in map inside cursor. In 2nd box I have used list of data class operation is performing as above. My app is working both condition but I am curious to learn that will 2nd box use same amount of memory because in 2nd box we are creating multiple instances of data class while in 1st box we are just inserting data in single instance of map. Thanks
    j
    j
    • 3
    • 5
  • g

    glenkpeterson

    01/20/2022, 4:12 PM
    It's really cool that Kotlin is multi-platform: JVM, JS, and Native! I remember reading something about how this was achieved, but can't find it now. Does it use a standard transpiler? Where can I dig into how this is achieved?
    c
    • 2
    • 2
  • r

    Rajkumar Singh

    01/20/2022, 10:55 PM
    is there more Kotlin-y idiomatic way(s) to express the following code snippet:
    val exitProcessing: Boolean? = func2call(tId, fId)
    if (exitProcessing == null || exitProcessing == true) return
    j
    e
    • 3
    • 4
  • c

    Colton Idle

    01/21/2022, 6:29 AM
    I want to find an item in a list. When I find it, I also want the index of it. I have found
    list.indexOfFirst
    and
    list.first
    but is there some way to get both?
    e
    a
    • 3
    • 6
  • a

    althaf

    01/21/2022, 6:38 AM
    hi is there better kotlin idiom for this one ?
    if (currencyInfo == null) {
        val assetData =
            JsonParser.getJsonDataFromAsset(context, "country_currency.json").orEmpty()
        currencyInfo = Gson().fromJson(assetData, CurrencyInfoResponse::class.java)
    }
    g
    j
    +2
    • 5
    • 7
  • h

    holgerbrandl

    01/21/2022, 1:47 PM
    Aren't == and
    equals
    synonyms in kotlin?
    data class Foo(val value: Double)
    
    Foo(3.0) == 3.0  // fails to compile with "Operator '==' cannot be applied to 'Foo' and 'Double'"
    Foo(3.0).equals(3)  // compiles
    v
    j
    e
    • 4
    • 7
  • j

    Javier

    01/21/2022, 2:10 PM
    line length default value has been moved to 120?
    k
    d
    • 3
    • 2
  • l

    Lokik Soni

    01/21/2022, 4:59 PM
    I am new to Android Clean Architecture and trying to implement it in my project but all I learnt doesn't match to my case. What I learnt is data layer consist app data related stuf like network api data, local room db data. But data for my app is 1. Broadcast receiver to get battery data. 2. RingtoneManager to get list of system ringtone. 3. Shared preference. So here I am confuse in which layer should I put all these stuff like if I put broadcast receiver in data layer then how to register it with activity. And can I put RingtoneManager and shared pref in data layer.
    t
    • 2
    • 1
  • v

    v79

    01/21/2022, 9:20 PM
    Does Kotlin's LinkedHashMap use reference identity or equals() in its
    get()
    method? I have two different objects with the same values, and an overridden equals method which returns true. But as a key to hashmap, they don't match.
    j
    e
    • 3
    • 7
  • s

    Shalom Halbert

    01/22/2022, 9:41 PM
    Is it possible convert
    Int.MAX_VALUE
    to a
    Double
    ? I’ve tried
    toDouble()
    , but that outputs 2.147483647E9
    e
    j
    • 3
    • 12
  • u

    Umar Ata

    01/23/2022, 9:26 AM
    Hi Why Android studio is still providing gradle files in groovy, even kotlin scripts are working perfectly fine? Any idea how can I create a new project in Android studio that generates kotlin scripts gradle files not groovy
    t
    v
    l
    • 4
    • 10
  • l

    loke

    01/23/2022, 1:26 PM
    @holgerbrandl almost synonyms. They added some static type checking so obviously incorrect comparisons like the one you showed fails at compile time.
    :thread-please: 1
    h
    • 2
    • 1
  • p

    Philip Hagen

    01/24/2022, 8:52 AM
    Hey all! Thanks for having me here. I’m just starting to learn Kotlin, after mainly working with Ruby and Elixir in recent years. If anyone has any tips or good resources feel free to share them. Thank you. 🙇
    j
    s
    +3
    • 6
    • 9
  • d

    dave08

    01/24/2022, 3:11 PM
    How could I get the enum value using Android WorkManager's Data::getString's value:
    @ExperimentalStdlibApi
    inline fun <reified T> Data.getValue(obj: Any?, prop: KProperty<*>): T {
        return when(T::class) {
            String::class -> getString(prop.name) as T
            Int::class -> getInt(prop.name, -1) as T
            Boolean::class -> getBoolean(prop.name, false) as T
            Enum::class -> getString(prop.name)?.let { enumValueOf<T>(it) } // This doesn't compile...
            else -> error("Trying to retrieve invalid type in Data for ${prop.name}: ${T::class}")
        }
    }
    j
    j
    • 3
    • 13
  • a

    acoconut

    01/25/2022, 6:21 PM
    Question about mapstruct! I have this POJO:
    data class WorkOrderCommentFilter constructor(
        val pagination: WorkOrderCommentPaginationFilter? = null,
        val id: Int? = null,
        val workOrderId: Int? = null,
        val comment: String? = null,
        val checkpointTypeName: String? = null,
        val createdAt: LocalDateTime? = null,
    )
    and this POJO:
    @Introspected
    data class WorkOrderCommentFilterDto constructor(
        @field:[QueryValue Parameter(description = "Pagination object")]
        val pagination: WorkOrderCommentPaginationFilter? = null,
        @field:[QueryValue Parameter(description = "Comment Id", example = "1")]
        val id: Int? = null,
        @field:[QueryValue Parameter(description = "WorkOrder Id", example = "1")]
        val workOrderId: Int? = null,
        @field:[QueryValue Parameter(description = "Comment message")]
        val comment: String? = null,
        @field:[QueryValue Parameter(description = "CheckpointType name")]
        val checkpointTypeName: String? = null,
        @field:[QueryValue Parameter(description = "Comment creation date")]
        val createdAt: Long? = null,
    )
    when I use a mapper like this:
    @Mapper(componentModel = "jsr330", uses = [LocalDateTimeLongMapper::class])
    interface WorkOrderCommentMapper {
         fun toDao(workOrderCommentFilterDto: WorkOrderCommentFilterDto): WorkOrderCommentFilter
    }
    The implementation is not right:
    @Override
    public WorkOrderCommentFilter toDao(WorkOrderCommentFilterDto workOrderCommentFilterDto) {
        if ( workOrderCommentFilterDto == null ) {
           return null;
       }
    
       WorkOrderCommentFilter workOrderCommentFilter = new WorkOrderCommentFilter();
    
       return workOrderCommentFilter;
    }
    I feel like I must be missing something, right? Thanks for any help in advance!
    :thread-please: 1
    m
    • 2
    • 6
  • g

    Greg Rynkowski

    01/26/2022, 10:16 AM
    Question about generics. Having this code:
    // all T - java classes implementing ViewDataBinding, each providing a static `bind` method
    // ViewDataBinding - a Java abstract class (with no declaration of `bind`)
    
    interface BindingAware<T : ViewDataBinding> {
        var f: T
    
        fun bind(v: View) {
            // f = T.bind(a)  // <= how to call static method provided by class behind T?
        }
    }
    How to call static method of T, having only T?
    r
    • 2
    • 1
  • a

    Arun Joseph

    01/26/2022, 12:22 PM
    I am using data class as immutable single state being emitted from view model. I print the entire state object when it is emitting, Is there a way to find which property is last updated ?
    data class SomeState(
        val property1: String,
        val property2: String
    ) {
        override fun toString(): String {
            return "property XX updated"
        }
    }
    j
    • 2
    • 3
  • j

    Jasin Colegrove

    01/26/2022, 2:15 PM
    https://kotlinlang.org/docs/object-declarations.html#companion-objects under companion objects there is this "Class members can access the private members of the corresponding companion object." Can someone show me the extent of what this means with a code example?
    l
    • 2
    • 1
Powered by Linen
Title
j

Jasin Colegrove

01/26/2022, 2:15 PM
https://kotlinlang.org/docs/object-declarations.html#companion-objects under companion objects there is this "Class members can access the private members of the corresponding companion object." Can someone show me the extent of what this means with a code example?
l

Leon W

01/26/2022, 2:21 PM
class CompanionTest {
    companion object {
        private val defaultName = "name"
    }

    var name = defaultName
}
We can assign the private member
defaultName
, which is located in the companion object, to the class member
name
.
View count: 4