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

    LastExceed

    05/29/2021, 7:15 AM
    why shouldn't i always go with the latest minor version of everything ? eg in build.gradle.kts instead of
    kotlin("jvm") version "1.5.10"
    i'd just do
    kotlin("jvm") version "1.5.+"
    afaik breaking changes only happen across major version updates so "auto bumping" the minor version should be fine ?
    c
    e
    • 3
    • 6
  • s

    Slackbot

    05/29/2021, 7:27 AM
    This message was deleted.
    l
    • 2
    • 1
  • j

    Jorkoh

    05/29/2021, 12:43 PM
    Why do I lose precision when using Duration from kotlin.time with some values?
    // 18 minutes and 17.1 seconds => 1097.1 seconds => PT18M17.099999999S
    val duration = 1097.1.toDuration(DurationUnit.SECONDS)
    print(duration.toIsoString())
    This loss of precision also exists if I use the
    toComponents
    extension or
    inWholeX
    accessors
    d
    • 2
    • 10
  • l

    LastExceed

    05/29/2021, 10:01 PM
    why is
    x.Y
    not allowed ?
    Untitled.cpp
    :blob-thinking-upside-down: 1
    🤔 2
    b
    a
    +2
    • 5
    • 6
  • d

    Daniele Segato

    05/30/2021, 12:24 PM
    how would you write a
    ReplaceWith
    for this:
    @Deprecated("Use BigDecimal for prices")
    fun Double.formattedWithCurrency(locale: Locale = Constants.LOCALE): String {
        return toBigDecimal().formattedWithCurrency(locale)
    }
    or for this constructor?
    @Deprecated("Use the constructor with BigDecimal(s)")
    constructor(
        originalPrice: Double?,
        price: Double,
        locale: String,
        percentage: Double?
    ): this(
        originalPrice = originalPrice?.toBigDecimal(),
        price = price.toBigDecimal(),
        locale = locale,
        percentage = percentage?.toBigDecimal()
    )
    n
    • 2
    • 6
  • c

    carbaj0

    05/30/2021, 4:32 PM
    What is the most efficient way to modify the values of an immutable
    Map<K,V>
    using is Key?
    d
    r
    m
    • 4
    • 10
  • r

    Ran Magen

    05/30/2021, 7:12 PM
    x-post..
    • 1
    • 1
  • l

    Luigi Scarminio

    05/31/2021, 1:27 PM
    Hello, My company restricts access to certain URLs. And it seems that the URL for the Kotlin compiler is blocked. Can someone point me the URLs for Kotlin ecosystem that are needed? Including Kotlin JVM and Kotlin Native
    ➕ 1
    s
    g
    • 3
    • 8
  • p

    Pablo

    05/31/2021, 2:07 PM
    How do I change this List<T>?
    data class Foo (val id: String, val name: String)
    val fooList = listof<Foo>(Foo("1","foo1"),Foo("2","foo22)
    Imagine I get this 
    fooList
     as a parameter and I want to update this list, do I need to do a 
    clone
      of the list and then a 
    copy
     of the 
    data class
     and update there the values? If i want to find first in the list of fooList if the id is equals 1 then change the "foo1" to another string is there any way to avoid to add an else? Otherwise the ide is complaining because I'm not using the result of copy.
    fun whateverFun(list: List<Foo>, predicate: Int){
      val foundValue = list.find{it.id == predicate}
      foundValue?.let{
        it.copy(title = "foo3"
      }
    }
    The only way to avoid this warning is to do an if else of a map and in the else remain the same value as it was I did it but I do not like tis..
    list.map { example -> if(example.id == predicate){example.copy(title="foo3")}else{example.copy(it.title)}
    n
    s
    j
    • 4
    • 15
  • a

    Alexander Suraphel

    05/31/2021, 5:06 PM
    Hi all, is there a discord group for kotlinlang or is this the definitive hang out place for kotlin folks?
    ➕ 1
    l
    r
    +2
    • 5
    • 7
  • l

    LastExceed

    05/31/2021, 6:45 PM

    https://i.imgur.com/NluduIk.png▾

    any way i can work around this problem ? i want to be able to instantiate
    Y
    with either a
    String
    or an
    X
    d
    l
    k
    • 4
    • 7
  • s

    seongsu kim

    06/01/2021, 7:08 AM
    Any idea about this error? Please Help me.
    ➕ 1
    d
    • 2
    • 3
  • s

    Shabinder Singh

    06/01/2021, 10:15 AM
    Github Apparently Changed Code Color of Kotlin from Orangish :large_orange_circle: -> Purple :large_purple_circle: I personally liked orangish color better... 🙃
    🚲 1
    ➕ 2
    b
    i
    i
    • 4
    • 5
  • u

    ubu

    06/01/2021, 1:12 PM
    Hello guys. In the following class:
    sealed class GUIModel {
        
        abstract val id: Id
        
        interface Selectable {
            val isSelected : Boolean
        }
        
        data class Model1(override val id: Id, override val isSelected: Boolean) : GUIModel(), Selectable
        data class Model2(override val id: Id, override val isSelected: Boolean) : GUIModel(), Selectable
        data class Model3(override val id: Id) : GUIModel()
    }
    is there a way to create a copy of the instance with updated
    isSelected
    field? Without having to check the type:
    fun GUIModel.createCopyWithUpdatedSelection(isSelected: Boolean) : GUIModel {
            return when(this) {
                is Model1 -> this.copy(isSelected = isSelected)
                is Model2 -> this.copy(isSelected = isSelected)
                is Model3 -> this
            }
        }
    and without switching to
    var
    in
    Selectable
    interface. Thanks!
    m
    • 2
    • 1
  • t

    Tony

    06/01/2021, 3:10 PM
    Hello all, I am using a Webview, and I was wondering how to use
    evaluateJavascript(...)
    to set a javascript variable to a javascript object.
    val javascriptString = "javascript: someString = {\"key\":\"value\"}"
    webView.evaluateJavascript(javascriptString, null)
    This is not working. Can someone point me in the right direction?
    :not-kotlin: 4
    z
    t
    • 3
    • 3
  • c

    carbaj0

    06/01/2021, 4:00 PM
    Do you make sense to have a specialized function to add an item to an immutable List?, something like this: (in the collections package i mean)
    fun <T> Collection<T>.plusHead(element: T): List<T> {
        val result = ArrayList<T>(size + 1)
        result.add(element)
        result.addAll(this)
        return result
    }
    n
    • 2
    • 3
  • e

    Erik

    06/01/2021, 7:28 PM
    When overriding your operator overloads, you can omit `operator`:
    (https://github.com/JetBrains/kotlin-web-site/blob/f3096d05fdfbc29ec4a704f42112028cdc7f48b7/docs/topics/operator-overloading.md#L15-L21) Why? Isn't it a bit implicit to override an operator, but not mark it as being an operator? I mean: if you'd override an operator without the keyword, you'd have to check the super declaration whether or not it actually is an operator. In turn, that can be an override without the keyword, all the way to the topmost declaration. I guess this is a non-issue because you wouldn't do this often. Without the explicit keyword it might be difficult to discover that a function is actually an
    operator
    , so that you could use the operator syntax instead of a regular function invocation (e.g.
    obj.invoke()
    vs
    obj()
    ).
    n
    p
    t
    • 4
    • 15
  • l

    LastExceed

    06/02/2021, 7:30 AM
    what access modifier should unit tests have ?
    c
    n
    +2
    • 5
    • 6
  • l

    LastExceed

    06/02/2021, 9:33 AM
    how do i get rid of "unused symbol" warnings when developing an api wrapper library? do i just turn off the inspection for the project ?
    g
    c
    n
    • 4
    • 6
  • r

    rajendhiraneasu

    06/02/2021, 11:42 AM
    Wanna get the first character of the first two words from the string, below is my code snippet can any one help to optimize it?
    val lbl = {txt:String -> txt.toCharArray()[0].toString()}
    
    val username = "Rajendra prasad guru" 
    val initials = username.split(" ").let {
        val l = lbl(it[0])
        if(it.size>1) "$l${lbl(it[1])}" else l
    }.toUpperCase()
    println(initials)
    
    Output is :RP
    d
    c
    n
    • 4
    • 16
  • l

    LastExceed

    06/02/2021, 12:01 PM
    what exactly is the difference between
    B
    and
    D
    here (other than the name) ? I've noticed that in
    B
    i can use
    super.x
    which i can't do in
    D
    , but there doesn't seem to be any use in that since bot
    x
    and
    super.x
    point to the same variable note: i know that
    A
    technically doesn't need to be
    abstract
    in this example. just assume that there's other abstract properties that require
    A
    to be
    abstract
    Untitled.cpp
    d
    • 2
    • 8
  • c

    Colton Idle

    06/02/2021, 4:14 PM
    Can anyone update kotlin plugin to 1.5.10 from within AS?
    p
    • 2
    • 4
  • l

    LeoColman

    06/02/2021, 8:02 PM
    Hi guys! I'm having some troubles with Kotlin + Antlr. I have this class:
    package br.com.colman.dicehelper
    
    
    import br.com.colman.dicehelper.br.com.colman.dicehelper.Dice
    import org.antlr.runtime.ANTLRStringStream
    
    public fun String.dice(): List<Dice> {
        DiceNotationLexer(ANTLRStringStream(this))
        return emptyList()
    }
    But the compiler warns me (via gradlew compileKotlin)
    Type mismatch: inferred type is ANTLRStringStream but CharStream! was expected
    ANTLRStringStream is a Java class, and it's definition is
    public class ANTLRStringStream implements CharStream {
    I assume that the "Type Mismatch" is wrong, as ANTLRStringStream is a CharStream, but it seems that the Kotlin compiler isn't very happy. Does anybody know how what is going on here?
    • 1
    • 2
  • m

    Manuel Pérez Alcolea

    06/02/2021, 8:23 PM
    I've noticed that companion objects behave in a lazy-fashion of sorts. For example, having
    open class B() {
        init {
            println("Instance of B created!")
        }
    }
    
    class A {
        companion object Companion: B()
    }
    B's
    init
    won't be called unless I access
    A
    in any way, or create an instance of it (
    A.Companion
    ,
    A()
    ). So this isn't just like Java's
    static
    (as the docs point out anyway: "Note that, even though the members of companion objects look like static members in other languages, *at runtime those are still instance members of real objects, and can, for example, implement interfaces*"). But this lazy-thing is something I wasn't expecting. Can I expect this behaviour no matter the platform?
    e
    • 2
    • 2
  • a

    Ankit Dubey

    06/03/2021, 9:53 AM
    I’ve issue in building KMM project
    val ktorHttpClient = HttpClient(OkHttp) {
    
        engine {
    
        }
    I need OkHttp in my HttpClient. This is in shared/commonMain. But commonMain not able to access OkHttp. If I add OkHttp in commonMain then getting build error.
    implementation ("io.ktor:ktor-client-okhttp:$ktorVersion")
    Failed building KotlinMPPGradleModel
    org.gradle.internal.resolve.ArtifactNotFoundException: Could not find ktor-client-okhttp-1.6.0-samplessources.jar (io.ktor:ktor-client-okhttp:1.6.0).
    j
    • 2
    • 6
  • s

    Slackbot

    06/04/2021, 12:49 PM
    This message was deleted.
    g
    a
    • 3
    • 2
  • d

    dead.fish

    06/04/2021, 2:17 PM
    Hi all! I’m getting a weird
    AbstractMethodError
    when I try to call a
    fun interface
    method with Kotlin 1.5:
    // definition
    fun interface OnItemClickListener {
      fun onChannelClicked(channelId: ChannelId)
    }
    
    internal var clickListener: OnItemClickListener? = null
    
    // callsite
    holder.itemView.setOnClickListener {
      clickListener?.onChannelClicked(channelId)
                     // ^^^ line 63, crash here
    }
                    
    // Runtime crash
    java.lang.AbstractMethodError: abstract method "void path.to.ChannelItemViewAdapter$OnItemClickListener.onChannelClicked-Grz9ttw(java.lang.String)"
      at path.to.ChannelItemViewAdapter.onBindViewHolder$lambda-3$lambda-2(ChannelItemViewAdapter.kt:63)
      at path.to.ChannelItemViewAdapter.lambda$CKDKaveMGRwL-cim-kOMtD1bOuU(Unknown Source:0)
      
    // decompiled Kotlin
    public interface OnItemClickListener {
      void onChannelClicked_Grz9ttw/* $FF was: onChannelClicked-Grz9ttw*/(@NotNull String var1);
    }
    
    public final void onClick(View it) {
      ChannelItemViewAdapter.OnItemClickListener var10000 = this.this$0.getClickListener$communication_debug();
      if (var10000 != null) {
        var10000.onChannelClicked-Grz9ttw(this.$this_with.getChannelId-WlYWy3A());
      }
    }
    Any idea what the culprit might be here?
    e
    • 2
    • 16
  • p

    Piyush Kukadiya

    06/04/2021, 3:18 PM
    Can anybody let me know IntelIJ-community package for lint tool source on github ?
    s
    • 2
    • 2
  • u

    user

    06/04/2021, 4:33 PM
    Kotlin IDE Performance The performance of your tools, and especially your IDE, has a significant impact on your development experience. For a long time, performance was a pain point for Kotlin developers, especially those who worked with large codebases or with complex code structures. This is why for the past year we’ve been focusing on improving this experience […]
    c
    • 1
    • 2
  • t

    turansky

    06/04/2021, 6:39 PM
    Is it legal to declare same public
    typealias
    in different modules? Like this one:
    package react
    
    typealias FC<P> = FunctionalComponent<P>
    z
    a
    +2
    • 5
    • 10
Powered by Linen
Title
t

turansky

06/04/2021, 6:39 PM
Is it legal to declare same public
typealias
in different modules? Like this one:
package react

typealias FC<P> = FunctionalComponent<P>
z

Zach Klippenstein (he/him) [MOD]

06/04/2021, 7:04 PM
In the same package as well?
t

turansky

06/04/2021, 7:31 PM
Yes
It works, but it doesn't look legal :(
a

andylamax

06/04/2021, 10:21 PM
should not be legal
t

turansky

06/04/2021, 11:19 PM
Issue reported
k

kqr

06/05/2021, 1:09 PM
if it is same same is it a problem?
t

turansky

06/05/2021, 1:32 PM
Looks like bomb for me
d

dmitriy.novozhilov

06/06/2021, 7:21 PM
This is common problem from JVM world. Imagine that you have such module structure and classes in it (pure java):
// MODULE: lib1
public class A {
    public void foo() {}
}

// MODULE: lib2
public class A {
    public void bar() {}
}

// MODULE: app (depends on lib1 and lib 2)
public class Main {
    public static void test(A a) {
        a.foo(); // (1)
        a.bar(); // (2)
    }
}
Which line (
(1)
or
(2)
) will be assumed as compile error? What happend on runtime if we comment errornous line?
Answer is simple: classpath order. JVM, java and kotlin lives in assumption that for each fully qualified name can be found only one class (or none). So on jmv (and javac, and kotlinc) problem of different classes with same fqn is resolved very simple: some fqn is resolved to first class which was found on classpath of compilation session/runtime So even if we comment line
(1)
and it will be compiled successfully (because compilation classpath was
lib2.jar;lib1.jar
) there is no guarantee that this code won't throw
NoSuchMethodError
at runtime (where classpath can be
lib1.jar;lib2.jar
)
Unfortunately, there is no way to protect users from such kind of errors. Even if compiler will check that there are no clashes between names from compiled module and from dependencies or even between just names in dependencies (such check will cost a lot of performance), then there is no guarantee that on runtime there will be same versions of dependencies
View count: 6