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

    George Nacouzi

    07/31/2021, 10:49 AM
    Hello what architecture do you suggest for using KMM for android and ios ?
    j
    • 2
    • 2
  • s

    Stefan Oltmann

    08/02/2021, 8:33 AM
    I wonder if the the Kotlin stdlib comes with an alphanumeric comparator for "natural order" of file names like https://github.com/sawano/alphanumeric-comparator
    ✅ 1
    e
    • 2
    • 24
  • a

    Andrea Giuliano

    08/02/2021, 12:59 PM
    Hi, I was trying to experiment a way to intersect two series in Kotlin efficiently. I have my Range class (similar to Kotlin in a way) defined as
    data class Range(
        val start: Int,
        var steps: Int,
        var repeat: Int
    )
    In practice a Range(2, 2, 5) represents the following sequence:
    2, 4, 6, 8, 10
    Now I want to write a function
    intersect(other: Sequence): Sequence
    that given 2 sequences is able to intersect them. Now I’m aware that I can go into the Kotlin ranges and/or build an array and do intersect on them. However what I was trying to do is to find a more efficient (constant) solution just using math. So I came up with this implementation
    data class Range(
        val start: Int,
        var steps: Int,
        var repeat: Int
    ) {
    
        fun intersect(other: Range): Range {
            val delta = leastCommonMultiple(steps, other.steps)
            val maxStart = max(start, other.start)
            val minStart = min(start, other.start)
            val start = minStart + (delta * ((maxStart - minStart + delta - 1)/delta)) //this is wrong
            val repeat = stepsTo(maxStart, delta, min(getLast(), other.getLast()))
    
            return Range(
                start,
                delta,
                repeat
            )
        }
    
        private fun stepsTo(start: Int, delta: Int, target: Int): Int {
            return  (target - start + delta - 1)/delta
        }
    
        private fun greatestCommonDivisor(a: Int, b: Int): Int {
            return if (a == 0) b else greatestCommonDivisor(b % a, a)
        }
    
        private fun leastCommonMultiple(a: Int, b: Int): Int {
            return a / greatestCommonDivisor(a, b) * b
        }
    
        private fun getLast() =
            start + steps * (repeat - 1)
    }
    But still the way start is calculated is wrong since it doesn’t place the number in the sequence.. I wonder if anyone has solved this problem already and in case you have any suggestion?
    p
    a
    • 3
    • 4
  • b

    Benoît Liessens

    08/02/2021, 6:59 PM
    How do I specify a default value for a function type parameter? e.g. I want to make the
    action
    parameter optional by giving it a default "no-op" value
    fun move(predicate: (Node<T> -> Boolean), action: (Node<T> -> Unit)) {
       // body
    }
    e
    • 2
    • 2
  • t

    Tower Guidev2

    08/04/2021, 2:40 PM
    Hi
    h
    r
    j
    • 4
    • 8
  • m

    MisileLab

    08/04/2021, 3:06 PM
    I want to make rhythm game with kotlin. Can you recommend kotlin game development engine?
    l
    • 2
    • 1
  • s

    Sergey Permiakov

    08/04/2021, 7:48 PM
    Hi, is there a way to use Windows Bluetooth api in Kotlin JVM?
    j
    • 2
    • 4
  • z

    zsperske

    08/04/2021, 8:02 PM
    Generics question, I’ve defined an interface for my factories and I’m trying to create a mapping so I can pass in the class of an Event & get back the factory which can create it.
    interface SchemaFactory<in E: Event, out S: Schema> {
    
      fun create(event: E) : S
    }
    
    class TestEventFactory : SchemaFactory<TestEvent, TestEventSchema>
    
    private val factories: Map<Class<out Event>, SchemaFactory<Event, Schema>> = mapOf(TestEvent::class.java to TestEventFactory())
    However I get the following error message on `factories`:
    Type mismatch.
    Required:
    Map<Class<out Event>, SchemaFactory<Event, Schema>>
    Found:
    Map<Class<out Event>, TestEventFactory>
    r
    e
    • 3
    • 13
  • m

    MisileLab

    08/05/2021, 12:39 AM
    My Code
    fun changeIntToDouble(number: Int) {
        return number.toDouble()
    }
    but my ide said Type mismatch: inferred type is Int but Unit was expected How can I fix it?
    r
    v
    • 3
    • 3
  • m

    MisileLab

    08/05/2021, 5:04 AM
    how to wait in kotlin? ex)
    fun kotlinlol {
        println("1")
        // sleep 1 sec
        println("2")
    }
    k
    s
    • 3
    • 2
  • a

    Ayfri

    08/05/2021, 11:08 AM
    Hi, I have a question, why is the Kotlin SDK defining extensions methods of classes that haven't any parent or not implementing anything ? Is that better than defining the method inside the class ? What are the benefits so ?
    r
    d
    +3
    • 6
    • 25
  • m

    MisileLab

    08/06/2021, 4:34 PM
    how to make keyboard listener in kotlin? not android
    m
    c
    r
    • 4
    • 5
  • g

    Gordon Child

    08/06/2021, 8:08 PM
    I'm having trouble with the kotlin syntax for methods that appear to have a vararg as the first parameter. I'm trying to call
    line.split(": ", 2)
    (line is a String). I've tried
    line.split(": ", false, 2)
    and
    line.split(delimiters = ": ", limit = 2)
    e
    • 2
    • 5
  • a

    Ayfri

    08/08/2021, 2:42 AM
    Hi, is it possible to have a default value for a generic type of a class ? Like that code in TypeScript :
    class Test<T = string> {
        readonly thing: T
    }
    
    const a = new Test() // this works
    const b = new Test<number>() // this too
    n
    j
    +2
    • 5
    • 8
  • s

    Slackbot

    08/09/2021, 3:05 AM
    This message was deleted.
    c
    m
    • 3
    • 2
  • a

    althaf

    08/13/2021, 1:19 PM
    Hi
    enum class Role(val letter: Char) {
        APPROVER('U'),
        ADMIN('D'),
        INQUIRER('R'),
        OPERATOR('O');
    }
    we have create this enum for code readability and we don't have direct control over how server is returning constants for the user roles, so they have done it this way 'U' , R etc apiRespose.role = "U" Role.valueOf(apiResponse.role) will not work ,as it is expecting  'APPROVER' as input . How can i achieve same benefit of Role.valueOf( ) wrt ot the 'letter' attribute in the enum
    a
    h
    +2
    • 5
    • 6
  • a

    althaf

    08/14/2021, 3:09 PM
    Hi i have a data class in domain layer and data layer, both has same attribute names, is there way in kotlin to initialized the domain model with the data model, if they have same attribute names ? domain layer model data class JourenyId ( val jr001, val jr002 ... ) data layer data class ApIResponseJourenyId ( val jr001, val jr002 ... )
    e
    t
    • 3
    • 2
  • d

    David Khol

    08/15/2021, 9:37 AM
    Hi! 🙂 I am seeing a lot of developers ignoring structured concurrency by launching a new coroutine in a different scope, although they are already in a suspending function or have access to
    CoroutineScope
    . Real life example which I came across so many times can be a convenience method like this:
    fun launchWithLoading(action: suspend () -> Unit) {
        scope.launch {
            try {
                loading = true
                action()
            } finally {
                loading = false
            }
        }
    }
    Nothing prevents the developer from calling it in a suspending context like:
    suspend fun alreadySuspending() {
        launchWithLoading {
            // do stuff
        }
    }
    or like
    fun first() {
        launchWithLoading {
            another()
        }
    }
    
    fun another() {
        launchWithLoading {
            // calculate something
        }
    }
    although rarely they intend to break the structured concurrency. I wonder if there is something like Android Lint but that is purely for Kotlin? Almost everything I've found on the internet points me in the direction of Android Lint. But since this unrelated to Android, I would like to solve it without coupling the solution to Android or Android Studio, so that it can be potentially used in IntelliJ IDEA as well.
    d
    e
    t
    • 4
    • 11
  • k

    Klitos Kyriacou

    08/16/2021, 2:58 PM
    Considering this class:
    open class KotlinPractice(val id: Int) {
        override fun equals(other: Any?) =
            this === other ||
                    other != null &&
                    other::class == KotlinPractice::class &&
                    (other as KotlinPractice).id == id
    
        override fun hashCode() = id
    }
    Is there a reason
    other
    is not smart-cast and instead I have to cast it to KotlinPractice manually?
    l
    e
    v
    • 4
    • 13
  • w

    wrongwrong

    08/16/2021, 8:06 PM
    Hi. I was trying to see if I could get some information from a
    KFunction
    without
    kotlin-reflect
    (using
    kotlinx-metadata-jvm
    ), but I couldn't get
    Metadata
    with valid information, so I have a question. What I want to achieve is as follows. 1. get the information of arguments and return values from
    KFunction
    . 2. get
    javaConstructor
    or
    javaMethod
    from
    KFunction
    .
    • 1
    • 3
  • l

    Lucas Marques

    08/18/2021, 5:27 PM
    Hi folks! I don't know if this is the best channel to ask you this, be here we go: I have an application built with Spring Boot and Gradle, which connects with Kafka and PostgreSQL. I'm using
    resources/application.yml
    as the config file. I want to create a specific package for each of this kinds of tests: unit, integration and end-to-end, but now I have a package only for unit tests. The problem is: every time I run the unit tests, my Spring Boot application try to connect with Kafka and Postgres (but for this purpose, I don't need them). How can I avoid to connect with these tools when running my unit tests? Also, do you know some blog post or documentation that shows how to create distinct packages for each kind of tests? Thanks in advance 🙂
    k
    h
    +2
    • 5
    • 6
  • d

    Danish Ansari

    08/19/2021, 7:06 AM
    Hi everyone, Is there anything available for Kotlin(or Java) similar to https://github.com/SBoudrias/Inquirer.js? I found https://github.com/kotlin-inquirer/kotlin-inquirer but when I run it on windows CLI(which is my project's primary target), the CMD goes brrrrrrr.... 😅 The inputs keep appearing again and again and doesn't wait for the user to give input
    e
    y
    • 3
    • 11
  • d

    David Smith

    08/19/2021, 10:21 AM
    I had a thread going in #general that I can no not reply to, what should I do?
    t
    e
    +2
    • 5
    • 7
  • p

    Pitel

    08/19/2021, 11:33 AM
    I have many `enum`s with the following prototype:
    enum class SomeHeaders(val label: String)
    (for headers of different tables). How can I write a type parameter (like
    val a: ???WHAT???
    ) so that it will be clear that it's
    enum
    (so I can use
    values()
    , etc.) and it had the
    label
    parameter. The parameter has easty solution: interface, but what about the
    enum
    limitation?
    r
    • 2
    • 5
  • w

    William Reed

    08/19/2021, 1:26 PM
    if a currently experimental annotation becomes no longer required in the future - will there be a compiler warning telling us that we no longer need to opt in? Looking at
    kotlin.contracts.ExperimentalContracts
    specifically
    i
    • 2
    • 2
  • s

    smallufo

    08/19/2021, 3:40 PM
    Hi , is there any way to get all
    sealed interface
    implementations ? ( Maybe classes or objects )
    h
    e
    • 3
    • 5
  • n

    nilTheDev

    08/19/2021, 4:49 PM
    Something is wrong with my code that works with File IO.
    fun main() {
        val strs = listOf(
            "line1",
            "line2"
        )
        val writer = File("src/main/resources/logging/temp.txt")
            .writer()
    
        strs.forEach { writer.appendLine(it) }
        writer.close()
    }
    The
    temp.txt
    file is empty when I run this program. After that the contents of the
    temp.txt
    file looks something like this,
    line1
    line2
    This is a perfectly reasonable output. However, things go wrong when I run a slightly modified version of the code for the second time.
    fun main() {
        val strs = listOf(
            "line3",
            "line4"
        )
        val writer = File("src/main/resources/logging/temp.txt")
            .writer()
    
        strs.forEach { writer.appendLine(it) }
        writer.close()
    }
    This is the new version. But this time the
    temp.txt
    file wasn't empty. It had the output of the first program saved into it. However, after running the new version the
    temp.txt
    file looks like this,
    line3
    line4
    The contents written by the first program are completely wiped out. Isn't the
    temp.txt
    file supposed to look like this?
    line1
    line2
    line3
    line4
    If not then what's even the point of using
    append
    over
    write
    ? Isn't
    append
    expected to write new content after the previously added content instead of wiping out and starting afresh? Or, am I missing something?
    k
    p
    +2
    • 5
    • 11
  • f

    Florian

    08/19/2021, 11:07 PM
    if Kotlin's
    fixedRateTimer
    function appropriate and accurate enough to create a countdown timer? And is there any problem with launching a coroutine inside the timer action block?
    fun startTimer() {
            timer?.cancel()
            applicationScope.launch {
                val selectedTask = selectedTask.first()
                if (selectedTask != null) {
                    taskDao.updateLastActiveTimestamp(selectedTask.id, System.currentTimeMillis())
                    startTimerService()
                    timerRunningFlow.value = true
                    timer = fixedRateTimer(period = TICK_DELAY) {
                        applicationScope.launch {
                            taskDao.increaseMillisCompletedToday(selectedTask.id, TICK_DELAY)
                        }
                    }
                }
            }
        }
    e
    g
    • 3
    • 15
  • n

    nilTheDev

    08/20/2021, 5:26 AM
    Can't import
    kotlin.io.path
    . Tried invalidating caches and restart. Still no luck. Any idea on how to make this work?
    k
    i
    • 3
    • 6
  • a

    Ayfri

    08/20/2021, 6:26 AM
    Hi, what is the Kotlin equivalent of
    Long::longValue()
    : https://www.geeksforgeeks.org/long-longvalue-method-in-java/ ?
    e
    • 2
    • 2
Powered by Linen
Title
a

Ayfri

08/20/2021, 6:26 AM
Hi, what is the Kotlin equivalent of
Long::longValue()
: https://www.geeksforgeeks.org/long-longvalue-method-in-java/ ?
e

ephemient

08/20/2021, 7:24 AM
none. Kotlin will automatically box to Long/unbox to long (as does Java since 1.5). the compiler will emit bytecode that calls Long.longValue() as needed
a

Ayfri

08/20/2021, 7:25 AM
ah, okay thanks !
View count: 4