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

    jaqxues

    05/19/2020, 2:02 PM
    Lets say I have this
    class Preference<T : Any> private constructor(
            val key: String,
            val default: T,
            val type: KClass<T>
    )
    
    // Extension Function
    fun getPref(): T { // This should be a nullable generic set by the preference
        // parse and return pref
    }
    Now, not every preference is not-null. So how can I omit
    <T: Any>
    to get to
    <T>
    so the preference itself can set itself nullable only via its type generic? The problem is that KClass does not like <T> and requires <T: Any> is there any smart way to get a not-null type generic from a nullable one? Or a reified function way to handle that?
    m
    l
    +2
    • 5
    • 24
  • o

    Orhan Tozan

    05/19/2020, 4:17 PM
    Why does the following code compile?
    fun <T, R> Result<T>.letIfSuccess(
        block: (data: T) -> Result<R>
    ): Result<R> = when (this) {
        is Result.Failure -> this
        is Result.Success -> block(this.data)
    }
    letIfSuccess returns
    Result<R>
    , but returns
    Result<T>
    when first branch of when statement is met. I would expect it to give it a compile error, as
    Result<T> !is Result<R>
    .
    r
    • 2
    • 2
  • e

    elect

    05/20/2020, 9:11 AM
    I have the following
    class Function1<A : Number, R : Number>(val func: (a: A) -> R) {
        operator fun invoke(a: A): R = func(a)
    }
    why
    ::invoke
    seems to require a parameter of type
    Nothing
    here:
    when(val f = t.function) {
        is Function1<*, *> -> f.invoke(stack.pop()) // Type mismatch: required Nothing
    }
    Because of the
    <*, *>
    ? I cant specify anything else because of type erasure this works though
    is Function1<*, *> -> (f as Function1<Number, Number>)(stack.pop())
    m
    • 2
    • 2
  • n

    Nikhil

    05/20/2020, 10:09 AM
    Hi, is there any Jmeter alternative written in Kotlin ?
    m
    • 2
    • 2
  • j

    Javier

    05/20/2020, 10:25 AM
    Is there any way to say to the compiler that use smart cast without having to use the variable assignment?
    m
    • 2
    • 3
  • j

    Joan Colmenero

    05/20/2020, 11:28 AM
    Hello I have a class like this :
    class MyResponse : ArrayList<MyResponseItem>
    How do I create an object of MyResponse with a list of MyResponseItem?
    m
    j
    • 3
    • 6
  • e

    elye

    05/20/2020, 12:19 PM
    https://stackoverflow.com/questions/61912898/mutablemap-setvalue-function-no-longer-exist
    d
    • 2
    • 4
  • b

    bmarinovic

    05/20/2020, 1:42 PM
    Hi, I’m curious if this can be rewritten with
    when
    block (
    hasMaxRole
    is extension method on my
    User
    data class):
    if (loggedInUser.hasMaxRole(<http://Role.NO|Role.NO>_ROLE)) {
        ResponseEntity(HttpStatus.FORBIDDEN)
    } else if (loggedInUser.hasMaxRole(Role.USER_ROLE)) {
        if (loggedInUser.id == id) {
            ResponseEntity.ok(loggedInUser)
        } else {
            ResponseEntity(HttpStatus.FORBIDDEN)
        }
    } else {
        userApiService.findById(id)
    }
    I would like something like this:
    when(loggedInUser) {
        hasMaxRole(<http://Role.NO|Role.NO>_ROLE) -> ResponseEntity(HttpStatus.FORBIDDEN)
        hasMaxRole(Role.USER_ROLE) && (loggedInUser.id == id) -> ResponseEntity.ok(loggedInUser as Any)
        hasMaxRole(Role.USER_ROLE) ->  ResponseEntity(HttpStatus.FORBIDDEN)
        else -> userApiService.findById(id)
    }
    (even with this code, I am repeating
    loggedInUser
    in second match since I need to call it twice in && operation)
    j
    • 2
    • 11
  • p

    pp.amorim

    05/20/2020, 1:56 PM
    Hi guys, I have a string interpolation in my software and I have this situation below happening:
    val intValue: Int = 2498533
    val foo = "<http://abc.com/$intValue|abc.com/$intValue>"
    println("Foo: $foo") //Foo: <http://abc.com/٢٤٩٨٥٣٣|abc.com/٢٤٩٨٥٣٣>
    But note that the interpolation is returning these non integer characters. Why this is happening? Shouldn’t it be
    <http://abc.com/2498533|abc.com/2498533>
    ?
    m
    j
    • 3
    • 10
  • e

    Ellen Spertus

    05/20/2020, 10:22 PM
    I have a
    List<String>
    and a function
    f: String -> T?
    and would like to apply
    f
    to each element
    s
    of the list in order until
    f(s)
    is non-null, returning that
    f(s)
    . If
    f(s)
    is null for all values,
    null
    should be returned. Here’s an ugly implementation:
    fun g(list: List<String>): String? =
        if (list.isEmpty()) {
            null
        } else {
            f(list.first()) ?: g(list.subList(1, list.size))
        }
    Can someone suggest a more elegant way? Here’s the code, if you’d like to play with it. https://pl.kotl.in/mByy6tkph
    m
    p
    +3
    • 6
    • 25
  • i

    Ifvwm

    05/21/2020, 5:49 AM
    how to clear a ByteArray? var aob = ByteArray(1024)
    n
    m
    • 3
    • 3
  • i

    Ifvwm

    05/21/2020, 6:12 AM
    hello, anyone here?
    🇳🇴 2
    :yes: 2
    :thread-please: 1
    m
    • 2
    • 1
  • u

    Uziel Sulkies

    05/21/2020, 6:25 AM
    Hi, Yesterday I discovered that kotlin allows this sort of code:
    data class Thing (
        val prop: String
    ) {
    
      private fun getProp(): Int = 5
    }
    Although this code won’t compile:
    data class Thing (
        val prop: String
    ) {
    
      private fun getProp(): String = "a"
    }
    with error “Platform declaration clash: The following declarations have the same JVM signature (getProp()Ljava/lang/String;)” The first one compiles successfully, and the
    getProp
    function can be either
    private
    or
    public
    . In Java, the same code won’t compile:
    public class Test {
    
      private String prop;
    
      public final String getProp() {
        return prop;
      }
    
      public void setProp(String prop) {
        this.prop = prop;
      }
    
      private final int getProp(){
        return 5;
      }
    }
    With error: “‘getProp()’ is already defined in ‘com.ni.monday.model.domain.webhooks.events.Test’” So why is it allowed in Kotlin? The consequences of this is this bug, I opened yesterday on #jackson-kotlin : https://github.com/FasterXML/jackson-module-kotlin/issues/341
    p
    • 2
    • 1
  • j

    James Richardson

    05/21/2020, 8:33 AM
    This is not a bug. It's just that kotlin is a different language from java.
    :thread-please: 1
    u
    l
    • 3
    • 2
  • e

    elect

    05/21/2020, 1:01 PM
    do you think the factorial can benefit from a
    tailrect
    function?
    var result = 1
    for (i in 1..a)
        result *= i
    result
    🇳🇴 1
    m
    m
    s
    • 4
    • 7
  • s

    Sam Garfinkel

    05/21/2020, 6:26 PM
    Is there a built-in contract for verifying that, if a Map contains key
    k
    then
    Map[k]
    is non-null? Or do I need to write my own?
    r
    k
    • 3
    • 8
  • l

    Leon johnson

    05/21/2020, 8:02 PM
    Whenever I upload an image from my gallery the image always return rotated. How can I rotate these pictures back to the appropriate way?
    m
    m
    s
    • 4
    • 4
  • l

    Leon johnson

    05/21/2020, 11:56 PM
    I'm using a singleValueEventListener and I just want to return that data everytime it changes
    h
    • 2
    • 2
  • u

    ursus

    05/22/2020, 2:58 AM
    promoCodeGenerationCountExceeded
    is false when it should be true
    n
    • 2
    • 13
  • p

    Patrick

    05/22/2020, 11:07 AM
    message has been deleted
    g
    i
    n
    • 4
    • 6
  • s

    Shreyas Patil

    05/22/2020, 6:38 PM
    https://link.medium.com/sm7NfjtoH6
    i
    d
    j
    • 4
    • 3
  • s

    steenooo

    05/22/2020, 9:44 PM
    Is it possible to hide fields from toString in data classes? I have a problem where one class has a list objects. Each object contains a reference to the first class. This is causing a stackoverflow in toString
    l
    r
    m
    • 4
    • 3
  • k

    KBrewster

    05/23/2020, 2:20 PM
    Trying to understand coroutines better, if you use delay inside of a coroutinescope will it carry on doing other jobs on the thread during that time? Or what is the difference between delay and thread#sleep
    s
    • 2
    • 2
  • s

    Samkeene

    05/23/2020, 3:34 PM
    I want to use Kotlin Experimental Time in my project, but its a pain having to annotate so many places with
    @ExperimentalTime
    , is there a way to disable this requirement?
    b
    l
    • 3
    • 6
  • s

    Sam Garfinkel

    05/23/2020, 5:27 PM
    Does anyone have a recommended tool for generating null-safe (such as one that uses lateinit or requiresNotNull) builders for kotlin classes? I’d normally use named arguments and default params, but I need a builder to support interop with Java.
    r
    c
    • 3
    • 5
  • k

    Kroppeb

    05/24/2020, 5:23 PM
    I have spend 2 hours today figuring out why my code wasn't behaving. I got lucky cause I noticed I was running code in file I shouldn't have been in, and remember I read somewhere that interface delegation with default methods don't get delegated. I can't really find any information on when/if this issue will be fixed.
    • 1
    • 1
  • z

    zero_coding

    05/24/2020, 6:39 PM
    Does it exist in Kotlin ??? like in Scala to delay function implementation?
    k
    r
    • 3
    • 2
  • p

    pambrose

    05/24/2020, 7:36 PM
    Has anyone run into the problem of extremely long compileKotlin steps? I have a ktor app that is taking 10 mins in the compileKotlin gradle step. On occasion, builds will take the normal amount of time, but more often than not, I am stuck in the hell of a 10 min build time -- even after simple code changes in a single file I have a 16 core, 64GB MBP, so it is not a question of compute resources. I am able to rebuild other Kotlin projects in the expected amount of time. It is just a single ktor app that is giving me grief. Incredibly, the same project was compiling fine a few days ago. I have tried multiple JVMs and multiple machines (my travis builds are timing out after 11 mins). I have also tweaked every gradle build option I could find, but to no avail. Any thoughts or ideas would be greatly appreciated.
    p
    c
    j
    • 4
    • 4
  • m

    myaa

    05/24/2020, 10:54 PM
    does kotlin provide any list implementation that can do efficient (constant-time) cons/cdr, for use when designing tail recursive functions that operate on lists?
    r
    j
    k
    • 4
    • 5
  • i

    Ifvwm

    05/25/2020, 1:35 AM
    what does this@Class mean?
    n
    s
    • 3
    • 2
Powered by Linen
Title
i

Ifvwm

05/25/2020, 1:35 AM
what does this@Class mean?
n

Nikky

05/25/2020, 2:08 AM
this@Classname is usually when you want to use
this
from a class outside of current scope which may have a different
this
s

Shawn

05/25/2020, 2:11 AM
https://kotlinlang.org/docs/reference/this-expressions.html
View count: 4