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

    savrov

    11/04/2020, 11:49 PM
    Just met a behaviour that I don’t understand. I have a multi-module project, let’s say: A, B, C. The dependency between them is:  • A - doesn’t depend on other modules, • B - depends on A • C - depends on A and B In A and B modules I use some lib, for ex: Koin. To add this lib, I should add the next lines to each module’s gradle file:
    repositories {
       jcenter()
       maven { url = uri("<https://dl.bintray.com/ekito/koin>") }
    }
    and 
    dependencies {
          implementation("org.koin:koin-core:3.0.0-alpha-4")
    }
    I’m ok with that, but the thing I don’t understand, why I have to add a repository block to C module as well, while I don’t have a dependency on that lib in C module? Thank you in advance.
    i
    a
    • 3
    • 3
  • s

    Scott Christopher

    11/05/2020, 12:49 AM
    We're getting the following interesting error:
    java.lang.VerifyError: Bad type on operand stack
    Exception Details:
      Location:
        com/example/Foo.bar(Lkotlin/jvm/functions/Function3;)Lcom/example/Other$ThingConsumer; @13: invokespecial
      Reason:
        Type 'kotlin/jvm/functions/Function3' (current frame, stack[3]) is not assignable to 'kotlin/jvm/internal/Ref$ObjectRef'
    when attempting to use:
    runBlocking { consumer(connection, event) }
    where
    consumer: suspend (Connection, Event) -> Unit
    is passed into the function calling
    runBlocking
    . We can hack around it by replacing it with something like
    GlobalScope.async { consumer(connection, event) }.asCompletableFuture().get()
    but it's less than ideal 😬 This is using Kotlin 1.4.10 and kotlinx.coroutines 1.4.0. Any thoughts?
    e
    v
    • 3
    • 51
  • i

    Ifvwm

    11/05/2020, 4:01 AM
    how to create a (Mutable)Collection<String!> value?
    z
    j
    • 3
    • 4
  • p

    Paul Woitaschek

    11/05/2020, 8:04 AM
    Is it possible to exclude paths from
    explicitApi
    ? I want to enable it for a library but that library also exposes generated classes by sqldelight and I'd like to not fail the compilation on generated classes.
    i
    • 2
    • 3
  • k

    Kerem Aslan

    11/05/2020, 11:15 AM
    Can someone explain to me why the
    reduce
    signature is like:
    inline fun <S, T : S> Array<out T>.reduce(
        operation: (acc: S, T) -> S
    ): S
    While the
    fold
    signature is like:
    inline fun <T, R> Array<out T>.fold(
        initial: R,
        operation: (acc: R, T) -> R
    ): R
    Shouldn't
    reduce
    be able to take two independent types instead? Something like
    inline fun <S, T> Array<out T>.reduce(
        operation: (acc: S, T) -> S
    ): S
    For context, I am trying to use
    reduce
    with a
    long
    accumulator and a domain object I am using. Something like:
    myCollection.reduce { acc, myObject ->
        acc + myObject.myField
    }
    That doesn't work but this does:
    myCollection.fold(0) { acc, myObject ->
        acc + myObject.myField
    }
    This is counterintuitive and confusing.
    v
    • 2
    • 5
  • n

    nickheitz

    11/05/2020, 11:47 AM
    I've recently upgraded a project from kotlin 1.3.72 to 1.4.10. Suddenly I am experiencing error of the following kind:
    val deviceMap = mutableMapOf(
                    "organisationId" to authenticationData.organisationId,
                    "userId" to authenticationData.userId,
                    "deviceTemplateUuid" to AuthenticationService.DeviceTemplate.findById(authenticationData.deviceTemplateId).clientId,
                    "dateInstalled" to dateInstalled
            ).also {
                it.putAll(extraProps)
            }
    The variable "extraProp" is defined as Map<String, Any>. In the past, I'm certain kotlin would have interpreted the return from "mutableMapOf" as MutableMap<String, Any>, but now I'm suddenly getting the following compiler error: Kotlin: Type mismatch: inferred type is Map<String, Any> but Map<out String, {Comparable<{Instant & String & UUID}> & java.io.Serializable}> was expected Is it mandatory now that I give a type hint to the function as "mutableMapOf<String,Any>(...)" to avoid this Union type nightmare?
    k
    • 2
    • 1
  • p

    Pacane

    11/05/2020, 2:59 PM
    Is there a way to write code in such a way that the kotlin analyzer wouldn't complain about these variables being nullable? I'm paraphrasing my code here, but it looks like this
    val a: String? = ...
        val b: String? = ...
    
        if (listOf(a,b).any { it == null }) {
          return
        }
        
        val l = a.length // compiler complains here
    Basically I'm doing null checks in for a bunch of variables before doing something with them. Shouldn't the compiler know about
    a
    on the last line, not being null?
    d
    m
    +6
    • 9
    • 53
  • r

    Rob Elliot

    11/05/2020, 4:02 PM
    Do these functions already exist in the stdlib? I’m failing to find them, but bitter experience suggests that this may just be me being stupid…
    fun <T> populate(i: Int, f: (Int) -> T): List<T> = (0 until i).map(f)
    fun <T> populate(i: Int, t: T): List<T> = populate(i) { t }
    
    populate(4, "Hello") == listOf("Hello", "Hello", "Hello", "Hello")
    populate(4) { "Hello $it" } == listOf("Hello 0", "Hello 1", "Hello 2", "Hello 3")
    r
    b
    p
    • 4
    • 8
  • r

    Ryan

    11/05/2020, 5:38 PM
    That feeling when you are not on latest kotlin so you can’t use trailing comma.
    😂 8
    c
    v
    • 3
    • 3
  • l

    laith

    11/05/2020, 9:13 PM
    Hi all, do anyone knows if Jetbrains is planning any port of Jetpack Compose to iOS and the Web ?
    🎉 2
    a
    r
    r
    • 4
    • 6
  • j

    jeggy

    11/05/2020, 10:31 PM
    Is it possible to hide fields from the
    toString
    function on data classes? Can be with annotation or anything. I want to achieve something like this: https://pl.kotl.in/Ld0EBnHM1
    n
    j
    +2
    • 5
    • 11
  • m

    mplain

    11/06/2020, 11:23 AM
    I am so confused by kotlix.serialization it seems it is meant to serialize custom objects only, annotated with @Serializable I cannot figure out how to serialize a simple Map<K,V>
    v
    • 2
    • 2
  • s

    StragaSevera

    11/06/2020, 5:36 PM
    I have a syntetic example of a problem I'm trying to solve.
    class MyDelegatedProperty {
        var innerStr: String = ""
    
        operator fun getValue(thisRef: Any, property: KProperty<*>): String {
            return innerStr
        }
        operator fun setValue(thisRef: Any, property: KProperty<*>, value: String) {
            innerStr = value
        }
    
        fun doSomething() {
            println(innerStr)
        }
    }
    
    class Example {
        val str: String by MyDelegatedProperty()
    
        fun main() {
            // use the doSomething function from str
        }
    }
    Is this possible somehow? Can I access the object that is created by a delegated property?
    m
    • 2
    • 11
  • m

    Mark Buikema

    11/06/2020, 9:23 PM
    Hi, I need an immutable sorted map. Which type should I use? •
    mapOf()
    is not sorted •
    sortedMapOf()
    is mutable •
    hashMapOf()
    is mutable and not sorted •
    linkedMapOf()
    is mutable Any other suggestions?
    n
    r
    +5
    • 8
    • 45
  • a

    ArcticLampyrid

    11/07/2020, 2:56 PM
    Hi, I'm trying to modify the compiler plugin
    kotlin-serialization
    , but I failed to test the modified one in local. How can I use a local modified one when building?
    b
    • 2
    • 5
  • w

    william

    11/07/2020, 10:39 PM
    is there a way for me to ignore experimental warnings for the entire project through the top level
    build.gradle
    ?
    b
    a
    • 3
    • 6
  • a

    Animesh Sahu

    11/08/2020, 11:02 AM
    Any doc/article/reference for the new Kotlin's IR (intermediate representation)? The sources are so wide (even though well documented more than half of those), its hard to follow a path i.e. where to see and understand the things.
    • 1
    • 1
  • d

    Deactivated User

    11/08/2020, 12:37 PM
    Have somebody else noticed that github seems to not be syntax-highlighting Kotlin now? Could be a bug in their highlighters?
    ➕ 9
    a
    • 2
    • 1
  • t

    Trevor Ackerman

    11/08/2020, 2:19 PM
    Off topic question: does anyone who is using jetbrains spaces know if it supports real time collaborative source code editing ?
    v
    c
    • 3
    • 3
  • f

    Florian

    11/08/2020, 6:28 PM
    What is the benefit of putting values like this into a private object? Is the only purpose that we have the
    PreferencesKey.
    prefix?
    private object PreferencesKeys {
            val SORT_ORDER = preferencesKey<String>("sort_order")
            val HIDE_COMPLETED = preferencesKey<Boolean>("hide_completed")
        }
    a
    • 2
    • 18
  • a

    Alec Muffett

    11/08/2020, 10:38 PM
    Evening, all. I'm converting a project from Gradle-Kotlin to Maven, and in the process of migration have kicked up a worrying warning message. I'm not sure where to report it, suggestions, please?
    [INFO] --- kotlin-maven-plugin:1.4.20-RC:compile (compile) @ app ---
    WARNING: An illegal reflective access operation has occurred
    WARNING: Illegal reflective access by com.intellij.util.ReflectionUtil (file:/Users/alecm/.m2/repository/org/jetbrains/kotlin/kotlin-compiler/1.4.20-RC/kotlin-compiler-1.4.20-RC.jar) to method java.util.ResourceBundle.setParent(java.util.ResourceBundle)
    WARNING: Please consider reporting this to the maintainers of com.intellij.util.ReflectionUtil
    WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
    WARNING: All illegal access operations will be denied in a future release
    b
    • 2
    • 37
  • v

    V Badalyan

    11/09/2020, 1:03 AM
    Sorry for russian. народ, кто в тонкостях потоков хорошо разбирается. Задача на оптимизацию. Голову ломаю уже неделю. Решение на кончике но никак не обернется в готово. /Есть большой поток (стрим). Скажем CSV на гиков 100, (те его читать по кругу оч не эффективно). В нем содержатся скажем объекты
    data claaa D(vtype: string, value: int, dim1 ... dimX)
    где dimX - некоторые "классификации, дайменшены) Собственно я беру этот CSV - прогоняю через скажем 5 фильтров и остается у меня от общем массы по 1% в каждом из этих 5 флоу. Вопрос. Как эффективно также продолжая 1 проход отфильровать из 5 отдельных фору группу где di1 и dim2 и dim3 у элементов совпадают). Те сделать группировку по разрезу и отсеять где нет полного совпадения.... Завис Пока только смог сделать промежуточную фильтрацию "Явно не войдет" и дальше второй проход уже по (флоу в буфер/канал) каналам в который результат первого цикла. Есть идеи? Как можно не дожидаясь окончание потока получить на текущем результате пересечение и сразу же по нему отдельный поток/корутин .
    :kotlin-intensifies: 1
    🤷‍♂️ 1
    :party-parrot: 1
    😕 1
    z
    v
    i
    • 4
    • 8
  • n

    nbaztec

    11/09/2020, 8:54 AM
    Hi, is there a given pattern on when (and when not) to use
    check
    functions? We have a use-case where we'd like to throw a concrete custom Exception. What would be the ideal way to do it? Wrap it later, but use
    check
    try {
      check(<exp>){ "check failed"}
    }  catch(e: IllegalStateException) {
      throw CustomException(e)
    }
    or throw it directly,
    if (<exp>) {
      throw CustomException("check failed)
    }
    d
    v
    • 3
    • 2
  • c

    CLOVIS

    11/09/2020, 11:14 AM
    Do you think there is any performance difference between these two implementations?
    k
    • 2
    • 8
  • m

    Matej Drobnič

    11/09/2020, 11:35 AM
    Does anyone know why this doesn't compile? If I understand correctly: * T is
    String
    *
    in T
    means that I can pass T or any of its super classes *
    Any
    is superclass of
    String
    * so
    Container<in T>
    should accept
    Container<Any>
    right? Instead I get:
    Type mismatch.
    Required :String
    Found: Any
    Does anyone know the reason that this does not compile?
    k
    a
    • 3
    • 18
  • m

    Matej Drobnič

    11/09/2020, 11:52 AM
    Similar question to the above, but with covariance this time. If I undestand correctly: *
    T
    is String *
    out T
    means that String or any of its subtypes can fit this * Since
    String
    in
    methodB
    matches that, why I can't pass
    methodB
    into
    methodA
    ?
    Untitled
    p
    t
    • 3
    • 5
  • f

    Florian

    11/09/2020, 6:07 PM
    inline fun SearchView.onQueryTextChanged(crossinline listener: (String) -> Unit) {
        this.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return true
            }
    
            override fun onQueryTextChange(newText: String?): Boolean {
                listener(newText.orEmpty())
                return true
            }
        })
    }
    Do I understand that correctly, the
    crossinline
    modifier assures that we can't call return in the lambda we are passing to this function? Because if we don't call
    return
    here, we would leave the
    onQueryTextChange
    method.
    a
    l
    • 3
    • 5
  • d

    diesieben07

    11/09/2020, 9:07 PM
    Is there a channel I can go to for compiler plugin development (knowing that yes, it is an unsupported api)?
    f
    • 2
    • 2
  • d

    df

    11/09/2020, 10:06 PM
    why does (0..0).forEach { ... } iterate once instead of zero times?
    e
    n
    +2
    • 5
    • 18
  • i

    Ifvwm

    11/10/2020, 2:26 AM
    I'm trying to change a simple python to kotlin, but I don't know where is wrong, https://paste.ubuntu.com/p/zp4x9yz36X/
    n
    g
    a
    • 4
    • 31
Powered by Linen
Title
i

Ifvwm

11/10/2020, 2:26 AM
I'm trying to change a simple python to kotlin, but I don't know where is wrong, https://paste.ubuntu.com/p/zp4x9yz36X/
it's just simple post requests, but in the function step2(), it just doesn't work, I don't know why
but python and curl worked, something is wrong with httpurlconnection?
n

nanodeath

11/10/2020, 2:29 AM
recommend using an http library here, but I'm trying to see what's going wrong here. maybe you need to read the response and close the connection.
i

Ifvwm

11/10/2020, 2:31 AM
which http library you suggest? the official doc is here https://docs.confluent.io/5.5.2/kafka-rest/quickstart.html
g

gildor

11/10/2020, 2:33 AM
Probably use ktor-client is the easiest way, it has support of json parsing too
HttpUrlConnection also works, but it has very clunky interface and a lot of boilerplate
Also looks that you really don't need all those try/catch which rethrow exceptions
There are many Kotlin stdlib functions which can improve this code too
What is exactly doesn't work on step2?
i

Ifvwm

11/10/2020, 2:37 AM
step2 is subscription
curl -X POST -H "Content-Type: application/vnd.kafka.v2+json" --data '{"name": "my_consumer_instance", "format": "json", "auto.offset.reset": "earliest"}' http://49.5.6.84:8082/consumers/testName
curl -X POST -H "Content-Type: application/vnd.kafka.v2+json" --data '{"topics":["jsontest"]}' http://49.5.6.84:8082/consumers/testName/instances/my_consumer_instance/subscription
curl -X GET -H "Accept: application/vnd.kafka.json.v2+json" http://49.5.6.84:8082/consumers/testName/instances/my_consumer_instance/records
those three curl is step1 step2 and step3
step1 create an instace for consumer, step2 to subscript a topic, step3 to get messages from that topic, python code and curl worked well
but with kotlin, the step2 doesn't work, there's no response in step2, see https://docs.confluent.io/5.5.2/kafka-rest/quickstart.html
I also tried OkHttp, same as httpurlconnection
g

gildor

11/10/2020, 2:43 AM
What do you mean no response? I don't see that you read response on step 2
Also in docs there is no response
i

Ifvwm

11/10/2020, 2:48 AM
aha, after I add read in step2, it worked!
I add this
try {
        val reader: BufferedReader = BufferedReader(InputStreamReader(httpconn2.inputStream))
        val response = reader.readLine()
        println(response)

    } catch (exception: Exception) {
        throw Exception("Exception while push the notification  $exception.message")
    }
step2 worked! and step3 can get messgaes now
g

gildor

11/10/2020, 3:18 AM
I think your issue not even lack of reading, but because you do not close output stream
i

Ifvwm

11/10/2020, 3:20 AM
no, I tried to close the output stream, it still be error 500
g

gildor

11/10/2020, 3:23 AM
So, your “not working” was 500 error? 500 means server error, looks like a bug of server It still related to what kind api you use, using raw httpurlconnection or even Okhttp is kinda low level, and you have to handle all possible edge cases yourself, now your code is leaking connection
You should use
use
blocks to handle resources
Also there are many helper extensions which allow you to read input/output strwams
i

Ifvwm

11/10/2020, 3:42 AM
ok, I would try ktor-client, any other lib suggested?
a

Animesh Sahu

11/10/2020, 4:08 AM
You can have a look at Fuel if you just want to parse the response (as a Client)
https://github.com/kittinunf/fuel
g

gildor

11/10/2020, 4:09 AM
I would recommend Ktor/Retrofit.
View count: 1