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

    Ifvwm

    05/25/2020, 1:36 AM
    and return@func?
    n
    s
    • 3
    • 2
  • i

    Ifvwm

    05/25/2020, 3:05 AM
    what this
    fun Int.foo(){}
    ?
    z
    • 2
    • 1
  • i

    Ifvwm

    05/25/2020, 3:06 AM
    not
    fun foo(): Int {}
    :thread-please: 3
    d
    s
    • 3
    • 9
  • a

    Ananiya

    05/26/2020, 12:36 PM
    hi, i get an error while i am running request which the error is in this file at the query. they tell me
    must not have replace block. For dynamic query parameters use @Query
    .how do i fix this error?
    kt_kt.kt
    s
    • 2
    • 3
  • m

    myaa

    05/27/2020, 1:48 AM
    what's an idiomatic way of saying "if null, run this and return null"? kind of like how
    also
    runs a function and then returns the original value, except that i only want to run the function if the original value is null i've got something like
    value.takeIf { it >= 0 } ?: run { println("Warning: negative value"); null }
    except i'd like to avoid manually having to return null at the end of the
    run
    d
    b
    • 3
    • 3
  • p

    Paul N

    05/27/2020, 10:21 AM
    I have a list of valid ids in a complex class (in my example a Pair). I have a separate list of ids. What's the best way of filtering the lists of ids to only contain ids that are present in the first case ? I'm using map to convert the list of pairs to a list of ids and then using contains in the example below. Is there a better way ?
    @Test
        fun `test filter`() {
    
            val cars = listOf("1" to "Jag","2" to "Mini")
    
            val ids = listOf("1","2","3")
    
            val validIds = ids.filter { cars.map { it.first }.contains(it) }
    
            validIds `should equal` listOf("1","2")
    
        }
    b
    a
    • 3
    • 4
  • b

    Bernhard

    05/27/2020, 10:33 AM
    currently cleaning up a Java app so that I can convert it to Kotlin at some point. Which nullable annotation should I use? I'm on Java 11 and using Spring Boot so org.springframework.lang.NonNull would be available
    m
    • 2
    • 1
  • k

    Karlo Lozovina

    05/27/2020, 2:26 PM
    is it possible to define an Interface that only allows data classes as implementations?
    m
    • 2
    • 1
  • k

    Karlo Lozovina

    05/27/2020, 2:43 PM
    I'm a newcomer to Kotlin/JVM so I'm definitely doing something non-idiomatic ... I'm used to structural equality from functional languages and I've had a few bugs because my classes weren't data classes...
    s
    d
    +5
    • 8
    • 17
  • m

    Marc Knaup

    05/27/2020, 5:32 PM
    Cannot access class ’<class>’. Check your module classpath for missing or conflicting dependencies
    What does this even mean exactly? I want to test code that depends on a certain library. But I cannot add that library to the test configuration, so I simply create some dummy classes with the same name & package name and mock them using mockk 🤔 Doesn’t seem to work though 😅
    a
    • 2
    • 6
  • v

    viralshah

    05/28/2020, 12:41 AM
    I would like to get a list of zoneddatetimes by hour between 2 zoneddatetimes
    val startTime = Instant.ofEpochMilli(1589778000000).atZone(ZoneOffset.UTC) // May 18 @ 05:00 UTC
    val endTime = Instant.ofEpochMilli(1589950800000).atZone(ZoneOffset.UTC) // May 20 @ 05:00 UTC
    
    val res: List<ZonedDateTime> = startTime.hoursUntil(endTime)
    
    //[May 19 05:00, May 19 06:00 ...]
    So that I can do a group by day on it
    val final = res.groupBy{it.day}.toMap()
    { May 18 -> 19 hours , May 19: 24 hours, May 20: 5 hours}
    Is this possible?
    m
    • 2
    • 2
  • b

    Brumelis Martins

    05/28/2020, 7:08 AM
    How would I write unit tests for this?
    CoroutineScope(Dispatchers.Main).launch {
        withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
            // do something here
        }
    }
    It always stops after withContext(Dispatchers.IO), im adding the TestCoroutineDispatcher @rule but it still does not work.
    a
    c
    • 3
    • 3
  • j

    Jody

    05/28/2020, 10:52 AM
    Hello guys, I have a problem when mocking a Kotlin class in Java with Mockito. The kotlin class has a
    reified
    method and my Mockito is presumably choosing the wrong method for some reason. So when running my tests, Mockito either chooses the method I want to mock or chooses the
    reified
    Kotlin method, which then turns into an Exception because the return types do not match. Did someone run into this problem already or know how to fix this?
    s
    t
    • 3
    • 16
  • e

    elect

    05/28/2020, 12:14 PM
    cant we apply the spread operator on
    List
    ?
    a
    b
    • 3
    • 2
  • j

    Jukka Siivonen

    05/28/2020, 12:55 PM
    is there a way to reference inline function in Java terms, I'm trying to create an ArchJUnit rule that specific function should not be used but how can I reference function without class name or fully qualified name
    s
    • 2
    • 3
  • j

    Jamie Taylor

    05/28/2020, 3:10 PM
    What's the general consensus on the best way to have a function that can fail in multiple different ways in Kotlin? I always thought we should use Result for that but just found out that it can't be the return type of a function. Should we just keep on throwing exceptions?
    c
    s
    s
    • 4
    • 17
  • s

    Sam Garfinkel

    05/28/2020, 3:11 PM
    Is there an idiomatic way to “bridge” inlined reified functions to concrete named functions so that the inlined function is callable from Java? Such as the following two prototypes.
    Untitled.kt
    h
    p
    s
    • 4
    • 24
  • m

    myaa

    05/28/2020, 6:20 PM
    how do i construct a class where 1. the fields of the class can be set using named constructor arguments with default values 2. those fields are accessible and settable through a map without having to declare each variable twice (once as a field and once as an argument)? so far i've got the following not-quite-working example
    class Test(
            first: String = "default",
            second: Int = 42,
            third: Boolean = false
    ) {
        val map = mutableMapOf<String, Any>()
    
        inner class MyDelegate(private val default: Any) {
            operator fun getValue(receiver: Test, property: KProperty<*>) =
                    map.computeIfAbsent(property.name) { default }
    
            operator fun setValue(receiver: Test, property: KProperty<*>, value: Any) {
                map[property.name] = value
            }
        }
    
        var first by MyDelegate(first)
        var second by MyDelegate(second)
        var third by MyDelegate(third)
    }
    
    val t = Test(second = 100)
    t.first = "test"
    println(t.map) // {first=test} - WRONG
    println("${t.first} ${t.second} ${t.third}") // test 100 false
    but i don't like the redundant definitions (having to declare each field as an argument as well), and this example also behaves incorrectly in that the map doesn't get populated with all the arguments immediately upon instantiation
    🤔 1
    s
    k
    m
    • 4
    • 18
  • k

    keturn

    05/28/2020, 6:28 PM
    dsl patterns can lead to nested receivers, e.g.
    project { all X@{ register {  
      foo(this@X)
    }}}
    is there a way for that inline receiver function to give the receiver an explicit name, other than
    this
    , instead of using the
    @
    label?
    s
    • 2
    • 6
  • g

    Gabe Kauffman

    05/28/2020, 11:06 PM
    Hello! Is it considered bad practice to define extension functions for native types, such as
    String
    ? Example, putting a function like this globally scoped in like a
    StringUtils.kt
    class:
    fun String.getLinkIfPresent(): String? {
        val m: Matcher = urlPattern.matcher(this)
        if (m.find()) {
            return m.group().trim()
        }
    
        return null
    }
    c
    j
    • 3
    • 4
  • m

    myaa

    05/28/2020, 11:17 PM
    running into some generics issues consider the following class hierarchy, consisting of a set of classes each with an associated "accessor". the idea is that e.g.
    Child1
    can be "accessed" using a
    Child1Accessor<T>
    object, which will return a value of type
    T
    .
    abstract class Accessor<T>
    
    abstract class Parent<A : Accessor<*>> {
        fun <T> access(accessor: Accessor<T>) : T = TODO("implement")
    }
    
    
    class Child1Accessor<T> : Accessor<T>()
    
    class Child1 : Parent<Child1Accessor<*>>()
    
    
    class Child2Accessor<T> : Accessor<T>()
    
    class Child2 : Parent<Child2Accessor<*>>()
    
    
    val myIntVal: Int = Child1().access(Child1Accessor<Int>())
    val myStringVal: String = Child1().access(Child1Accessor<String>())
    val error: Int = Child2().access(Child1Accessor<Int>()) // should be an error, wrong type of accessor
    my issue is: how do i restrict the
    accessor
    parameter of
    access
    to be a subclass of
    A
    , the accessor type specified for that class, without using wildcard types, so that i know the type parameter of the accessor? i tried the following:
    fun <T, V> access(accessor: V) : T
                where V : A,
                      V : Accessor<T> = TODO("implement")
    but this gives me a
    Type parameter cannot have any other bounds if it's bounded by another type parameter
    error
    h
    s
    • 3
    • 12
  • a

    Ali

    05/29/2020, 5:17 AM
    Can someone help me get FreeMarker working with IntelliJ, please? 🙂 I'm doing the Ktor beginner app and she no worky.
    🤔 1
    b
    • 2
    • 5
  • a

    aaverin

    05/29/2020, 12:32 PM
    I am migrating codebase from Rx1 to Rx2 and now that
    null
    is not supported by RxJava and RxKotlin, what is the strategy you use to have kind of null values? We have some places in codebase that were doing something like
    map {
      service.get() //can return null
    }.filterNotNull()
    It's too much effort to rewrite every service to not ever return null when before null was considered a valid empty value.
    j
    p
    • 3
    • 5
  • i

    iguissouma

    05/29/2020, 2:27 PM
    Hello, how can I use a copy method like for data class with a non data class? I have a class that initialize a date = now() but I want to change it for a test case!
    m
    j
    m
    • 4
    • 5
  • x

    xii

    05/29/2020, 4:37 PM
    quick question, im trying to use the find method, but for some reason it returns
    List<Test?>
    and I want it to be just a List<Test>. how do I prevent the type of the elements in the list to be nullable? I want it to be an empty list worst case scenario
    s
    • 2
    • 14
  • s

    Sebastien Leclerc Lavallee

    05/29/2020, 6:03 PM
    I have a function like this:
    public final GoogleSignInOptions.Builder requestScopes(Scope var1, Scope... var2) { }
    I can call
    .requestScopes(scope1, scope2, scope3)
    without any problem. How can I translate a list of Scopes to call this function. I tried using only an
    Array
    , a
    List
    , to pass the first element and then a list. But nothing worked. Seems like I have to pass the expanded list. How can I achieve this when my list of scopes is stored inside a
    List<Scope>
    ? Thanks!
    a
    • 2
    • 7
  • s

    Steve

    05/29/2020, 9:51 PM
    I'm trying to do something for a JSON parser. I have a bunch of properties named "%type%Sold" and "%type%Base" which contain a CountryCode and an amount. There's like 5 different times these repeat. I'm trying to figure out the best way to structure the model for this. I was trying to use sealed classes with data classes, but that seems rather unwieldy. Here's what I've got so far:
    sealed class Amount(
      val currency: Currency,
      val value: Long,
      val type: String
    ) {
      data class Sold(override val currency: Currency, override val amount: Long): Amount(currency, amount, "Sold)
    • 1
    • 1
  • n

    NurBahnhof

    05/29/2020, 9:58 PM
    I don't quite understand the scope in Kotlin Gradle DSL. I understand that gradle build script implicitly import some stuffs. But for example in this code:
    application{ mainClassName="SomeClass" }
    where do the name mainClassName come from? I'm setting some attribute here. But where is the object? Shouldn't it be something like:
    application.mainClassName="SomeClass"
    • 1
    • 1
  • c

    ClaudiuB

    05/29/2020, 9:59 PM
    Okay. I'm encountering, of all things, a potential critical bug with
    kotlin.collections.ArrayList.indexOf
    . I think it's critical, but maybe not. There are fixes but
    indexOf
    doesn't properly work for me in certain cases ( version 1.3.61) Premise:
    val questionsAndAnswers = mutableListOf<Any>()
    , in practice containing items of types data class Answer and data class Question. Both have
    equals(other: Any)
    overriden to return true only when other is of the same type. equals in Answer
    override fun equals(other: Any?): Boolean {
                return (other as? Answer)?.proof?.sourceNode?.getContentId() == proof?.sourceNode?.getContentId()
    }
    equals in Question
    override fun equals(other: Any?): Boolean {
                return (other as? Question)?.item?.getContentId() == item?.getContentId()
    }
    I do
    questionsAndAnswers.indexOf(answer)
    knowing my answers are only add odd indexes, and I get a 0. I expected either -1 or odd. Check the debugger, i mapped a bunch of data to help troubleshoot
    i
    a
    • 3
    • 11
  • s

    Shawn Karber_

    05/29/2020, 10:11 PM
    I need to make an Observable with n number of items in it, but I don't know how to achieve this. Here's the code I'm using as an example:
    device.establishConnection(false)
        .flatMap(rxBleConnection -> Observable.combineLatest(
            rxBleConnection.readCharacteristic(firstUUID),
            rxBleConnection.readCharacteristic(secondUUID),
            YourModelCombiningTwoValues::new
        ))
        .subscribe(model -> {
            // Process your model.
        });
    Here's the code I am trying to write:
    device.establishConnection(true)
        .flatMap { rxBleConnection ->
            val characteristicReads: MutableList<Single<ByteArray>> =
                mutableListOf()
            for (c in characteristics) {
                characteristicReads.add(rxBleConnection.readCharacteristic(c.uuid))
            }
            Observable.combineLatest(*characteristicReads)
        }
        .subscribe({ onConnectionSuccess(it) }, { onConnectionFailure(it) })
    The error is:
    Type mismatch.
       Required: ObservableSource<out TypeVariable(R)!>!
       Found: Unit
    v
    a
    • 3
    • 3
Powered by Linen
Title
s

Shawn Karber_

05/29/2020, 10:11 PM
I need to make an Observable with n number of items in it, but I don't know how to achieve this. Here's the code I'm using as an example:
device.establishConnection(false)
    .flatMap(rxBleConnection -> Observable.combineLatest(
        rxBleConnection.readCharacteristic(firstUUID),
        rxBleConnection.readCharacteristic(secondUUID),
        YourModelCombiningTwoValues::new
    ))
    .subscribe(model -> {
        // Process your model.
    });
Here's the code I am trying to write:
device.establishConnection(true)
    .flatMap { rxBleConnection ->
        val characteristicReads: MutableList<Single<ByteArray>> =
            mutableListOf()
        for (c in characteristics) {
            characteristicReads.add(rxBleConnection.readCharacteristic(c.uuid))
        }
        Observable.combineLatest(*characteristicReads)
    }
    .subscribe({ onConnectionSuccess(it) }, { onConnectionFailure(it) })
The error is:
Type mismatch.
   Required: ObservableSource<out TypeVariable(R)!>!
   Found: Unit
v

Vasile Glijin

05/30/2020, 1:05 PM
Check the signature on Observable.combineLatest(*characteristicReads)
a

araqnid

05/30/2020, 4:34 PM
don’t you need
*(characteristicReads.toTypedArray())
?
(or use a different method signature that takes a collection rather than a vararg)
View count: 3