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

    Gunslingor

    08/23/2020, 1:08 AM
    Any tips to avoid having to manually clear chrome browser cache everytime I change CSS? Not all things suffer from this, but the package I'm using seems to.
    d
    k
    • 3
    • 3
  • f

    frank

    08/23/2020, 8:37 AM
    In Java, When I had a function that returned an object and it could not pass the validations inside the function it returned a null value . Then I would checked the method if it returned null for the null-safety What approaches can I use to replace null? • Define Any type in the function and return my object or string etc.. ? • Return empty object ? • Suggestions ... Code for replace null:
    fun getParentPath(son :String) : Path {
        val parent = Paths.get(son).parent
    
        return parent?.let {
            if (Files.exists(parent))
                parent
            else null  // need alternative
        } ?: null     //  need alternative
    }
    👀 1
    f
    m
    n
    • 4
    • 4
  • r

    Rohan Maity

    08/23/2020, 10:19 AM
    Hello I have created
    Map<String,My_Info_Class>
    during annotation processing. So Map is created during compile time. Is there any way I could access the same
    Map object
    I created in Different module ?
    z
    • 2
    • 19
  • s

    Sam

    08/23/2020, 3:09 PM
    Ran into this, is there any reason why kotlin bytecode ignores synchronization primitive for get()
    var data = false
        @Synchronized get
        @Synchronized set(value) { field = !value }
    
    fun main() {
        println("Value $data")
    }
    The only way to get bytecode to call getData() is by having this redundant get (which is prompted as redundant getter in IDE)
    @Synchronized get() = field
    n
    a
    k
    • 4
    • 30
  • m

    melatonina

    08/23/2020, 7:54 PM
    Now I lost some code. "Focus on quality and performance"
    n
    • 2
    • 5
  • d

    df

    08/23/2020, 9:14 PM
    is there a way to construct an instance of KClass<Foo<Bar>> if all I have is an instance of KClass<Bar>?
    z
    • 2
    • 5
  • n

    Nikky

    08/24/2020, 12:46 AM
    was the 1.4.0 plugin removed from the repositories ? https://mvnrepository.com/artifact/org.jetbrains.kotlin.jvm/org.jetbrains.kotlin.jvm.gradle.plugin?repo=gradle-plugins
    j
    • 2
    • 3
  • a

    alwyn

    08/24/2020, 1:18 AM
    Since 1.4.0 the
    contentEquals
    method on classes like
    ByteArray, IntArray
    have been marked as deprecated. I am used to the Java world where a deprecation usually goes hand in hand with information on what can be used as an alternative. Does anyone know what can be used to compare the contents of arrays instead of contentEquals? It looks like this functionality eventually calls through to java.util.Arrays.equals which takes nullable values. So maybe this is to indicate that
    ByteArray?.contentEquals
    is supposed to be called and eventually the other version will just be dropped. Why not just drop it anyway in 1.4.0 already since it should just 'work'?
    n
    i
    • 3
    • 3
  • j

    Jukka Siivonen

    08/24/2020, 9:18 AM
    If I have a function with parameter param: () -> Boolean how can I call this function using method reference Foo:myFunction as a parameter?
    d
    • 2
    • 7
  • u

    user

    08/24/2020, 11:20 AM
    message has been deleted
    🤔 10
    j
    o
    +3
    • 5
    • 12
  • r

    Rob Elliot

    08/24/2020, 3:42 PM
    Mapping some data to kotlin I sometimes find myself doing something like this:
    data class A(
      val b: B
    ) {
      data class B(
        val c: C
      ) {
        data class C(
          val foo: String,
          val bar: Int
        )
      }
    }
    I find myself hankering after a more concise way of doing the same thing; something like:
    data class A(
      val b: data class B(
        val c: data class C(
          val foo: String,
          val bar: Int
        )
      )
    )
    I imagine those as being completely interchangeable - so the type of
    A.b.c
    is
    A.B.C
    . What do you think?
    🙈 2
    😱 1
    t
    n
    • 3
    • 12
  • s

    stephanmg

    08/24/2020, 3:49 PM
    Well, what do you want to achieve in the first place?
    :thread-please: 2
    🤨 1
    r
    j
    • 3
    • 20
  • s

    Steve

    08/24/2020, 4:36 PM
    of course, you might want to just pass that data class into your Portal class instead of creating it inside the Portal class
    f
    n
    • 3
    • 9
  • v

    Victor Harlan Lacson

    08/25/2020, 12:51 AM
    I have a kotlin multi-platform project with sub module
    build.gradle.kts
    below, but it is not creating a runable jar
    import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
    
    plugins {
        kotlin("multiplatform")
        java
        application
        id("com.github.johnrengelman.shadow") version ("5.2.0")
    }
    
    group = "com.kotlin.mpf.server"
    version = "1.0-SNAPSHOT"
    
    
    val ktorVersion = "1.4.0"
    
    repositories {
        //repos
    }
    
    kotlin {
        sourceSets {
            jvm().compilations["main"].defaultSourceSet {
                dependencies {
                    //--dependencies
                }
            }
        }
    }
    
    
    application {
        mainClassName = "com.vhl.inventory.server.MainKt"
    }
    
    tasks.withType<ShadowJar> {
        baseName = "kotlin-mpf-runnable"
        classifier = null
        version = null
    }
    when ever i try to run the created fat jar, follows an error below
    java -jar fat.jar
    
    Error: Could not find or load main class com.vhl.inventory.server.MainKt
    Caused by: java.lang.ClassNotFoundException: com.vhl.inventory.server.MainKt
    has anyone done runnable jar in multi-platform project
    n
    • 2
    • 1
  • t

    Tolriq

    08/25/2020, 7:05 AM
    I'm getting a very weird issue and wonder if someone have already seen that, before trying to find a small repro. On some suspending functions an Android TextView.getText().toString() == "" works but TextView.text.toString() == "" (As suggested by IDE and previously worked) triggers java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to java.lang.String. It's like in the second case the .toString() call is converted to a cast and not the proper toString()
    👀 2
    m
    • 2
    • 2
  • x

    xii

    08/25/2020, 11:58 AM
    I want to create an extension function to filter a list based on condition x, and if condition x returns an empty list, go for another condition, but I can't figure an idiomatic way to write it; here's what I've got:
    v
    m
    • 3
    • 7
  • s

    snowe

    08/25/2020, 5:59 PM
    no clue what I'm doing wrong with my mock (mockito-kotlin)
    @Nonnull
        String[] createSfdcObjects(@Nonnull final SObject... sfdcObjects);
    mock looks like
    whenever(sfdcCrudService.createSfdcObjects(anyVararg()))...
    , but it always returns null. I've tried every matcher (
    any
    ,
    anyOrNull
    , etc) and none of them match. What am I missing?
    e
    • 2
    • 13
  • p

    Philipp Mayer

    08/25/2020, 7:03 PM
    Hey guys, what's your preferred way to read xml files? We're currently using jackson, but it has a nasty bug with empty lists (https://github.com/FasterXML/jackson-dataformat-xml/issues/124). Unfortunately we don't have access to the output parameters of the xml, so we gotta find something else. Any recommendations?
    n
    v
    • 3
    • 6
  • v

    Vampire

    08/25/2020, 7:14 PM
    Can I somehow transform a
    .kt
    file with an object expression in it to the actual instance? Like with using
    K2JVMCompiler
    for example? Are there any examples for that?
    m
    h
    • 3
    • 12
  • t

    TwoClocks

    08/26/2020, 1:02 AM
    I have a val, except I don't know what it will be until way later (like after some network stuff). but once it's set it should be immutable. Is there a pattern for this type of thing? More of a FP question than kotlin I know.
    s
    n
    j
    • 4
    • 10
  • j

    Jakekudur

    08/26/2020, 3:18 AM
    hey! Can anyone suggest me how to implement this animation with motion layout?
    buy-now.webm
    :stackoverflow: 2
    l
    c
    • 3
    • 2
  • s

    Simon Lin

    08/26/2020, 7:07 AM
    val jobA = Job()
    val jobB = GlobalScope.launch(jobA) {
        delay(1000L)
        println("World!")
    }
    What is the different between
    jobA
    and
    jobB
    ? If I would like to cancel the Job, which one need to be called?
    jobA.cancel()
    or
    jobB.cancel()
    ?
    m
    • 2
    • 1
  • e

    Erik

    08/26/2020, 8:17 AM
    Would it be helpful if the Kotlin language would allow
    ?
    as an expression suffix to coerce the expression to be of nullable type? Examples:
    var x = 1?
    -> inferred type =
    Int?
    , so no need to type
    var x: Int? = 1
    . Later you can always set
    x = null
    .
    someQuery()?
    -> inferred type = nullable return type of
    someQuery()
    . If that function already returns a nullable type, then a linter warning should be shown that the
    ?
    suffix is redundant.
    c
    h
    y
    • 4
    • 15
  • m

    Marc Knaup

    08/26/2020, 10:56 AM
    The stdlib has this function:
    public inline fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : CharSequence, C : R =
        if (isEmpty()) defaultValue() else this
    But when copy&pasting that code it doesn’t even compile!
    Type parameter cannot have any other bounds if it’s bounded by another type parameter
    Is it safe to silence that error? 😮
    u
    • 2
    • 4
  • p

    Patrick Doering

    08/26/2020, 1:23 PM
    Hey, my name is Patrick and I am interested in the multiplatform feature of Kotlin.
    👋 2
    j
    • 2
    • 3
  • b

    blackstardlb

    08/26/2020, 1:54 PM
    anyone know how to import org.jetbrains.kotlin.gradle.targets.native.tasks.KotlinNativeHostTest_Decorated in groovy? I think i'm having issues because native is a keyword
    h
    • 2
    • 1
  • p

    poohbar

    08/26/2020, 2:49 PM
    Need a generics advise, how can I make the second override work?
    interface Animal {
        val id: String
        fun <T: Animal> withSound(sound: String): T
    }
    
    data class Dog(
        override val id: String
    ): Animal {
        // works
        override fun <T : Animal> withSound(sound: String): T {
            TODO("Not yet implemented")
        }
    
        // does not work
        override fun withSound(sound: String): Dog {
            TODO("Not yet implemented")
        }
    }
    k
    t
    t
    • 4
    • 5
  • p

    poohbar

    08/26/2020, 3:23 PM
    so yeah,
    withSound()
    should return the same type as it is defined in
    b
    • 2
    • 1
  • z

    zak.taccardi

    08/26/2020, 4:42 PM
    What’s the Kotlin equivalent of the Groovy
    List<T>.join(..)
    function?
    n
    n
    • 3
    • 9
  • b

    bbaldino

    08/26/2020, 9:26 PM
    I've got a use case where I iterate over a sequence of numbers to find the max, but I'd like to "quit early" if I find a value over a certain number and just return that as the max, is there a good way to do this? I could call
    .any { it > bigEnoughNum }
    first, but then if that returns false I have to iterate again to find the actual max, which doesn't seem efficient.
    n
    e
    +2
    • 5
    • 44
Powered by Linen
Title
b

bbaldino

08/26/2020, 9:26 PM
I've got a use case where I iterate over a sequence of numbers to find the max, but I'd like to "quit early" if I find a value over a certain number and just return that as the max, is there a good way to do this? I could call
.any { it > bigEnoughNum }
first, but then if that returns false I have to iterate again to find the actual max, which doesn't seem efficient.
n

nanodeath

08/26/2020, 9:27 PM
iterable.first { it > bigEnoughNum }
?
b

bbaldino

08/26/2020, 9:28 PM
Is that different from the
any
method? If it fails I'd still have to iterate over the whole list to find the max.
n

nanodeath

08/26/2020, 9:28 PM
it returns the thing that was > bigEnoughNum
or throws if there is none...but you can use
firstOrNull
or
find
the same exact way
b

bbaldino

08/26/2020, 9:29 PM
Ah, yes in my case I don't necessarily care about the specific value that's
> bigEnoughNum
e

ephemient

08/26/2020, 9:30 PM
it's an inline function, so (depending on the structure of your code)
iterable.maxByOrNull {
    if (it > bigEnoughNum) return
    it
}
will break early
b

bbaldino

08/26/2020, 9:31 PM
Good call...I thought about just doing a return but I was just thinking the local return wouldn't do much...so I could move this to another method and do that.
n

nanodeath

08/26/2020, 9:32 PM
or use
first
? I'm still unclear why that doesn't work
n

Nir

08/26/2020, 9:32 PM
first doesn't work because if no numbers are larger than bigEnoughNum
you have to do a second pass
to get the max
hmm i was thinking maxByOrnull could be used without refactoring but it's surprisingly tricky for type inference reasons
either that or I'm making a silly mistake
val x = listOf(1,10,11)
    println(x.maxByOrNull { if (it > 8) return@maxByOrNull it else it })
I expected that to print 10, but it prints 11
b

bbaldino

08/26/2020, 9:40 PM
Pretty sure
return@maxByOrNull
is the same as the normal return that happens there
So you'd need some other label, but I don't think that'd work with a sequence chain (don't think you can add a label there), so you'd have to do it in an enclosing method I think
n

Nir

08/26/2020, 9:43 PM
println(run { x.maxByOrNull { if (it > 8) return@run it else it }!! })
that'll do it
It's not the same btw
actuall I'm wrong
It's the same 🙂
So yeah, the run thing is the same, though at that point it might be messy enough to turn into a one liner anyway
b

bbaldino

08/26/2020, 9:46 PM
Yeah
n

Nir

08/26/2020, 9:48 PM
fun <T: Comparable<T>> Iterable<T>.maxOrOver(threshold: T) = this.maxByOrNull { if (it > threshold) return it else it}!!
👍 1
e

ephemient

08/26/2020, 10:07 PM
more general could be
inline fun <T: Comparable<T>> Iterable<T>.firstOrMaxOrNull(
    crossinline predicate: (T) -> Boolean
): T? = maxByOrNull { if (predicate(it)) return it else it }
not sure how general it should be, though. seems pretty specialized
s

streetsofboston

08/26/2020, 10:15 PM
What about using the takeWhile/takeUntil function?
b

bbaldino

08/26/2020, 10:16 PM
Oh, using that to 'short circuit' the sequence?
:yes: 1
That's a good idea...looks like that works
e

ephemient

08/26/2020, 10:22 PM
constructs a new list… but if that's acceptable then go for whatever is the clearest code for you
b

bbaldino

08/26/2020, 10:28 PM
Is that true in the sequence case?
n

Nir

08/26/2020, 10:38 PM
prob not but to use it on a sequence you'd need to do asSequence first which is annoying
It would be really nice if kotlin supported some form of "or" constraints on generics
it's so common to write functions that would work with either iterables or sequences
AFAICS you have to implement them twice basically
e

ephemient

08/27/2020, 12:09 AM
on JVM the compiler would either have to output multiple implementations or silently use reflection
Scala has union types and its approach is the latter
but also - iterable and sequence operations are significantly different in Kotlin
iterable operations are inline (they're all immediate, so early return etc. work), sequence operations are out-of-line (they're all lazy, so early return is impossible)
n

Nir

08/27/2020, 12:22 AM
Yes, I understand, but most likely when you implement the two it would defer down to other functions that had been implemented for both
in this example, maxByOrNull is already implemented in terms of both sequence or iterable
so you would write your function constrained to either sequence or iterable, with a single implementation which just calls maxByOrNull, which gets dispatched correctly based on which constraint is met
I've experienced this before; there's lots of useful functions you can write where the implementation for iterable and sequence is the same character by character, because your implementation is just calling down to things like
map
which are implemented for both (but with the differences you mentioned)
I guess one tricky thing is that you'd maybe want the iterable version to be inline but not the sequence. but if you can live with it not being inline 🤷
View count: 4