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

    Damian

    12/07/2019, 2:38 PM
    Is there a way to pass two functions at the same time via a lambda I have a following code
    rollButton.setOnClickListener { rollDice(diceImage1)}
    but want to call rollDice twice, with two different arguments e.g.
    rollButton.setOnClickListener { rollDice(diceImage1) rollDice(diceImage2)}
    k
    • 2
    • 4
  • b

    bjonnh

    12/09/2019, 3:31 AM
    I can't get the compiler to understand what I want to do with coerceIn
    ✔️ 1
    s
    • 2
    • 2
  • d

    Douglas KN

    12/10/2019, 4:05 PM
    How can I query jvm system property (eg in gradle
    jvmArgs "-Dfoo=true"
    ) from kotlin?
    d
    • 2
    • 2
  • f

    Florian

    12/11/2019, 9:42 AM
    This
    val healthBonus
    inside the init block doesn't make much sense, does it?
    t
    a
    • 3
    • 4
  • s

    Simon Kågedal Reimer

    12/11/2019, 12:39 PM
    I have a map that’s of type
    VertxHttpHeaders
    . That’s a type that implements
    Iterable<Map.Entry<String, String>>
    but it does not implement
    Map
    . I want to filter out some headers and get back a Map. This is what I’ve come up with:
    headers
        .map { it.toPair() }
        .toMap()
        .filterKeys { noCopyHeaders.contains(it).not() }
    Can I do better somehow? 🙂 I wish I didn’t have to do the two-step conversion to the map and I wish I had a `filterNotKeys`… I guess I could just add those as extensions
    d
    • 2
    • 2
  • j

    James Richardson

    12/11/2019, 2:19 PM
    Something like headers.filterNot { it.first in noCopyHeaders }.toMap
    s
    s
    m
    • 4
    • 8
  • h

    Hong Minhee

    12/12/2019, 7:50 PM
    Is there any convention about maximum columns like 80 or 120? I just read Coding Conventions in the Kotlin website, but it says nothing about maximum columns.
    s
    c
    +2
    • 5
    • 6
  • i

    Ive Vasiljevic

    12/13/2019, 9:46 AM
    Is there a lightweight JSON lib for Kotlin? For serialization and deserialization
    y
    k
    • 3
    • 2
  • h

    Hoanghun5

    12/14/2019, 11:12 AM
    Could someone tell me what is the correct way to benchmark ArrayList.add(index, element) method with JMH? I made one like this but note sure if it’s the correct approach:
    @BenchmarkMode(Mode.AverageTime)
    @Fork(2)
    @Measurement(iterations = 10)
    class MyBenchmark {
        @Benchmark
        fun testMethod(): Any {
            val list: List<Int> = ArrayList()
            for (i in 0 until NR_TO_INSERT) {
                list.add(list.size / 2, i)
            }
            return list
        }
    
        companion object {
            private const val NR_TO_INSERT = 500000
        }
    }
    h
    j
    • 3
    • 3
  • m

    Mr.NiceGuy

    12/15/2019, 12:40 PM
    Any idea why this is happening when I am trying to run TornadoFX application via intellij (with Gradle) but if I am compiling the project into far-jar it's running without any issue.
    😂 1
    📷 1
    r
    • 2
    • 2
  • j

    Jarek Rozanski

    12/15/2019, 2:31 PM
    Hey folks, question about
    .let
    and nullability. Code snippet:
    val foo : String? = "sample"
    foo.let { it.toUpperCase() }
    Results in:
    Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
    k
    m
    • 3
    • 6
  • b

    bjonnh

    12/16/2019, 3:50 AM
    I have a project that is Kotlin Backend (ktor, coroutines and kotlinx.serialization mostly) and the frontend is Vue. I would like to share some code between JS and Kotlin, especially regarding the serialization and the data classes. Can I expect being able to use a transpiled kotlin library from javascript or is Kotlin/JS only made to target directly the DOM and call other libs?
    • 1
    • 1
  • i

    Ive Vasiljevic

    12/16/2019, 9:46 AM
    Sealed classes don't work with Lists?
    s
    • 2
    • 2
  • p

    poohbar

    12/16/2019, 6:59 PM
    class MyClass<T> {
        var prop: T = null // error
    }
    why does this not work? I thought that the upper bound of a type parameter is by default
    Any?
    i
    • 2
    • 3
  • w

    Will Nixon

    12/17/2019, 12:31 PM
    Hi all, trying to set up my first ‘RecyclerView’ and a little confused as to why the View in class ViewHolder is unrecognized… noob to Kotlin and Android development, so trying to wrap my head around it
    import android.view.LayoutInflater
    import android.view.ViewGroup
    import androidx.recyclerview.widget.RecyclerView
    
    class EntryAdapter(private val context: SpeechPageActivity, private val entryList: Array<String>) : RecyclerView.Adapter<EntryAdapter.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EntryAdapter.ViewHolder {
            return ViewHolder(LayoutInflater.from(context).inflate(R.layout.entry_cell, parent, false))
        }
    
        override fun getItemCount(): Int {
            return entryList.size
        }
    
        override fun onBindViewHolder(holder: EntryAdapter.ViewHolder, position: Int) {
            holder.entryText?.text = entryList[position]
            holder.itemView.setOnClickListener {
                println(entryList[position])
            }
        }
    
        class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            val entryText = view.entryText
            val entryImage = view.entryImage
        }
    
    }
    a
    r
    p
    • 4
    • 9
  • o

    oday

    12/17/2019, 3:32 PM
    i need to use Kotlin for a technical interview, are the basic datastructures like graph and queue easily usable?
    s
    r
    b
    • 4
    • 29
  • o

    oday

    12/18/2019, 5:55 PM
    is there a one-liner for this? the bulk of the counting pairs part of the problem I mean, not the end aggregation (but also there as well)
    r
    • 2
    • 3
  • a

    am

    12/20/2019, 12:27 AM
    Hey folks may I know how can we original list to another list, problem I am facing any modifcation in copied list leads to modification in original list. May I know what needs to be done in kotlin
    s
    m
    j
    • 4
    • 3
  • l

    Lauritz Hilsøe

    12/20/2019, 9:56 AM
    I looked into kapt, kotlinpoet, AutoService, looked at many tutorials, but I can't get anything working unfortunately
    m
    s
    • 3
    • 2
  • d

    Dmitri Sh

    12/21/2019, 3:30 AM
    Good day today. The KMP project we have been working on for the annual CodeWeek event is a finalist! 250 teams competing, we are one of the top 25 going into the finals in January. WatchOS KTOR client made it just in the nick of time! Still needs polishing and a good amount of refactoring, but I think the main point proven - we share logic and networking across multiple targets (and planning to add more) https://github.com/dmitrish/kinsight-multiplatform
    r
    s
    • 3
    • 4
  • h

    Hullaballoonatic

    12/21/2019, 5:24 PM
    is there a better way to write this? (less verbose and less or equal impact)
    val height = points.maxBy(Point::y)!!.y - points.minBy(Point::y)!!.y
    I often find myself using this schema
    val height = points.map(Point::y).run { max()!! - min()!! }
    uses less characters but iterates an additional time through
    points
    of course if i really wanted to do it best by performance, i could accomplish this in only one iteration...
    a
    a
    • 3
    • 8
  • t

    Tuang

    12/23/2019, 4:16 AM
    hi all,, is there any method which convert list to int separate with ” , ” likes
    joinToString()
    I means
    val list = listOf(1,2,3)
    
    // i want the result like this
    // 1,2,3 <= each is int value
    t
    s
    +2
    • 5
    • 47
  • i

    Ive Vasiljevic

    12/23/2019, 1:07 PM
    Is it okay to nest sealed classes. So UserData is a part of ModelData, but UserData can also have its own hierarchy with two separate types of UserData, in this case LoginData and AuthenticationData. Or is there any better solution for this?
    Untitled
    m
    m
    • 3
    • 4
  • s

    Stefan Kanev

    12/24/2019, 12:32 PM
    So, I have a bunch of data immutable classes that make up a nested structure (represeting a GraphQL response) and I'd like to mutate one of the nested values to get an immutable copy. for example:
    data class User(val name: String, val location: Location)
    data class Location(val city: City, val somethingElse: String) // for example
    data class City(val name: String, val country: String)
    I have a user and I want to change the city name, getting a copy of user with everything else on the chain unchanged. I can do it with copy:
    val newUser = user.copy(location = user.location.copy(city = user.location.city.copy(name = "New name")))
    but that's far too long esentially I'd like to be able to do something shorter like:
    val newUser = user.copy { it.location.city.name = "New name" }
    I don't think the above could get gotten to work, but is there something in those lines I can do? (also, not my actual data structure, but sufficient for this example) Thanks 🙂
    r
    • 2
    • 6
  • e

    Egor Okhterov

    12/24/2019, 3:13 PM
    When you create default project there is the following in
    build.gradle
    :
    jvmJar {
        dependsOn(jsBrowserWebpack)
        from(new File(jsBrowserWebpack.entry.name, jsBrowserWebpack.outputPath))
    }
    How do you express that in
    build.gradle.kts
    ? Probably, I've got a part of this right, but I'm not sure about the last expression
    tasks.named("jvmJar") {
        dependsOn("jsBrowserWebpack")
    }
    d
    • 2
    • 13
  • b

    Bipul

    12/26/2019, 5:18 AM
    Hi there #getting-started which IDE should I use for kotlin+android development 🙂
    t
    s
    p
    • 4
    • 5
  • t

    Tuang

    12/26/2019, 10:03 AM
    hi guys i know how to print all of array element in one line
    val topStudents = arrayOf("Jake", "Jesse", "Matt", "Alec")
    names.forEach { println(it) }
    but how to do in this condition.
    val allStudents = setOf {
          "Michael",
          "Kim",
          topStudents <= i don't know how to retrieve topStudent each names likes "Michael" and "Kim" 
    }
    
    
    
    // the result what i want is 
    val allStudents = setOf {
          "Michael",
          "Kim",
          "Jake",
          "Jesse",
          "Matt",
          "Alec"
    }
    i
    b
    d
    • 4
    • 4
  • m

    Michał Kalinowski

    12/26/2019, 10:23 AM
    can someone help me with generics? lets say I already overload
    Number
    operators and now I want make generics
    Point
    that will also overload operators based on
    Number
    , f.e result of
    Point<Float> + Point<Float>
    should be
    Point<Float>
    but recently is
    Point<in Float>
    :<
    data class Point<Unit : Number>(val x: Unit, val y: Unit, val z: Unit) {
      operator fun plus(increment: Point<Unit>): Point<in Unit> {
        return Point(x + increment.x, y + increment.y, z + increment.z)
      }
    
      operator fun minus(increment: Point<Unit>): Point<in Unit> {
        return Point(x - increment.x, y - increment.y, z - increment.z)
      }
    
      operator fun times(increment: Point<Unit>): Point<in Unit> {
        return Point(x * increment.x, y * increment.y, z * increment.z)
      }
    
      operator fun div(increment: Point<Unit>): Point<in Unit> {
        return Point(x / increment.x, y / increment.y, z / increment.z)
      }
    }
    d
    s
    • 3
    • 5
  • i

    Ive Vasiljevic

    12/26/2019, 4:40 PM
    Is there any difference between nested sealed sub-classes and not nested sub-classes except for the way sub-classes are accessed?
    Untitled
    t
    k
    • 3
    • 4
  • a

    Alpesh Vas

    12/26/2019, 5:02 PM
    Hi, any idea why this function requires
    return
    statement in the end even if we are throwing exception
    onFailure
    fun<T> withRetryOnRateLimit(numOfRetries: Int = 10, func: () -> T): T {
        repeat(numOfRetries) {
            runCatching(func)
                    .onSuccess { return it }
                    .onFailure { throw it }
        }
    }
    s
    s
    • 3
    • 3
Powered by Linen
Title
a

Alpesh Vas

12/26/2019, 5:02 PM
Hi, any idea why this function requires
return
statement in the end even if we are throwing exception
onFailure
fun<T> withRetryOnRateLimit(numOfRetries: Int = 10, func: () -> T): T {
    repeat(numOfRetries) {
        runCatching(func)
                .onSuccess { return it }
                .onFailure { throw it }
    }
}
s

Simon Kågedal Reimer

12/26/2019, 5:21 PM
The throwing happens inside a callback block. You still need to return a T in the withRetryOnRateLimit method itself, as you are declaring that.
➕ 1
s

StavFX

12/26/2019, 7:05 PM
The compiler doesn’t know that it is guaranteed that either onSuccess or onFailure will get called (all it knows is that each will be called at most once). Which also makes me wonder what’s the point of the loop here? The first iteration is guaranteed to also be the last.
➕ 2
Also, I’m assuming that this is a simplified version of the code, because in its current form, it’s functionally identical to
return func()
View count: 2