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
getting-started
  • t

    Tuang

    02/18/2020, 3:20 AM
    In the following data, [MyData(name=mike, country=mm), MyData(name=tike, country=bkk)] how to retrieves all member of MyData and transform as one list? what i want to do is, [“mike”, “mm”, “tike”, “bkk”]
    l
    b
    • 3
    • 7
  • a

    am

    02/18/2020, 6:28 AM
    What is the best way to deepcopy a list, I am using the following way
    studentList.forEach {
    if(it.id ==student.id){
    list.add(it.copy(isFailed = false))
    }else{
    list.add(it)
    }
    }
    k
    z
    • 3
    • 3
  • j

    JP

    02/23/2020, 3:01 AM
    Why would this code not work?
    val f: (String) -> Unit = { it -> println(it.length) }
    val x = "hello".also(::f)
    This prints out these error messages:
    error: type inference failed: inline fun <T> T.also(block: (T) -> Unit): T
    cannot be applied to
    receiver: String  arguments: (KProperty0<(String) -> Unit>)
    
    val x = "hello".also(::f)
                    ^
    error: type mismatch: inferred type is KProperty0<(String) -> Unit> but (String) -> Unit was expected
    val x = "hello".also(::f)
                         ^
    While
    val x = "hello".also(::println)
    would work, why would above not? What is
    KProperty0<>
    ?
    k
    d
    • 3
    • 2
  • j

    JP

    02/23/2020, 5:35 AM
    Another question: Can one override a function with lambda expression? I was following the koans, and below code
    import java.util.*
    
    fun getList(): List<Int> {
        val arrayList = arrayListOf(1, 5, 2)
        Collections.sort(arrayList, object : Comparator<Int> {
            override fun compare = {x: Int, y: Int -> y - x}
        })
        return arrayList
    }
    gave me error messages:
    Object is not abstract and does not implement abstract member public abstract fun compare(p0: Int!, p1: Int!): Int defined in java.util.Comparator
    'compare' overrides nothing
    Expecting '('
    Can someone elaborate these messages? edit: additionally when I tried different codes in the line starting with
    override fun compare
    , 1.
    override fun compare(x: Int, y: Int) {
                return y - x
            }
    this did not work as well, producing error messages
    Return type of 'compare' is not a subtype of the return type of the overridden member 'public abstract fun compare(p0: Int!, p1: Int!): Int defined in java.util.Comparator'
    Type mismatch: inferred type is Int but Unit was expected
    I don’t understand the error message. Why was the expected type
    Unit
    , not
    Int
    ? Shouldn’t the compiler expect the return type as
    Int
    ? BUT 2. with a slight modification,
    override fun compare(x: Int, y: Int): Int {
                return y - x
            }
    this worked. 3.
    override fun compare(x: Int, y: Int) = y - x
    This works also. But in this case, I also didn’t explicitly write the return type, same as approach 1. What are the differences between them? Why did 1. produce error while the other two didn’t? What’s happening under the hood?
    k
    • 2
    • 6
  • t

    tim

    02/24/2020, 8:39 AM
    Hiya, I'm new to kotlin (coming from Typescript) and was curious what best practices people are using to managing app state? I've got a several projects I'm considering kotlin for (server, mobile, and web) and I'd love to have a shared core across all -- so this query isn't strictly about one setup. I am leaning towards the Flux/Redux design pattern as I am familiar with it and I think it makes sense once you've wrapped your head around unidirectional data flow. But I can't find much written about Kotlin + Flux. Is there a preferred approach someone here might be able to direct me to?
    r
    l
    • 3
    • 44
  • k

    keishi kubo

    02/24/2020, 1:59 PM
    I couldn’t understand inline function explanation. Can anyone explain ?
    Using higher-order functions imposes certain runtime penalties: each function is an object, and it captures a closure, i.e. those variables that are accessed in the body of the function. Memory allocations (both for function objects and classes) and virtual calls introduce runtime overhead.
    But it appears that in many cases this kind of overhead can be eliminated by inlining the lambda expressions.
    s
    e
    • 3
    • 5
  • k

    keishi kubo

    02/24/2020, 2:26 PM
    I might understand. Thank you! 🙂 Is such overhead so large that I should often care about ?
    e
    l
    • 3
    • 3
  • v

    vinny2020

    02/24/2020, 8:40 PM
    What is the underlying List type for Kotlins read only list?
    s
    c
    t
    • 4
    • 4
  • v

    vinny2020

    02/24/2020, 8:40 PM
    AbstractList ?
    n
    • 2
    • 7
  • e

    Ellen Spertus

    02/24/2020, 11:49 PM
    I’d like to read in a file and produce a
    Set<String>
    containing all of the words in the file. Is there a way to
    map
    or
    flatMap
    over the lines of a file? I’ve gotten as far as
    bufferedReader().useLines()
    .
    d
    s
    • 3
    • 10
  • j

    jk2018

    02/26/2020, 11:36 PM
    if I have a function at the top level of a file, not inside a class or an object, is there a way to get the name of the file , or the name of the function or if that doesn't work maybe the package ? (would like to log it)
    m
    s
    • 3
    • 6
  • n

    Nikita Khlebushkin

    02/27/2020, 8:21 PM
    Also asking here hoping to understand that part
    s
    • 2
    • 1
  • g

    Gilberto Diaz

    02/28/2020, 12:39 PM
    Hi to all, I started using Kotlin little over two month to write a library, since then I started listening to Talking Kotlin and I started to hear the concept of DSL. The more I hear DSL in a conversation, seems to me that what it means is a specific library that is going to be used within a specific language. I would like for someone to explain what are the cases where to can call some code base a DSL.
    r
    j
    +2
    • 5
    • 9
  • v

    vinny2020

    02/28/2020, 9:08 PM
    with Kotlin IDEA seems to prefer this myMap[mykey] over this myMap.get(mykey) , is that the more idiomatic way to do things?
    :yes: 14
    b
    • 2
    • 1
  • b

    bodiam

    03/01/2020, 2:23 AM
    Hi all, I was wondering if there's something like
    myMap.mapWithIndex { (index, key, value ) -> .... }
    available? I know it's possible with arrays, but I "need" to have an index counter (my current approach is just to have a counter var, but I was hoping there would be something more elegant)
    d
    i
    • 3
    • 6
  • c

    Chills

    03/01/2020, 5:57 AM
    like a must read
    l
    m
    +7
    • 10
    • 13
  • h

    hooliooo

    03/05/2020, 1:52 PM
    Is there a way to get the keypaths to a class’s companion object such as this:
    class Test {    
        companion object {
            const val A: Int = 0
    
            const val B: Int = 1
    
            const val C: Int = 2
    
            const val DInt = 3
    
            const val E: Int = 4
        }
    }
    This companion object will only have constant vals
    d
    p
    c
    • 4
    • 8
  • b

    bodiam

    03/06/2020, 7:05 AM
    What is the Java equivalent of this code:
    interface MyInterface<out T> {
        fun process(): T
    }
    I need to convert this interface to Java because of SAM conversion, but I'm failing a bit here.
    e
    b
    r
    • 4
    • 12
  • k

    Kirill Prybylsky

    03/06/2020, 8:44 AM
    What is the java equivalent of this code:
    Untitled
    n
    d
    +2
    • 5
    • 9
  • l

    LastExceed

    03/06/2020, 1:55 PM
    Why is Java code almost always notably harder to understand that Kotlin code? Whenever i look up code online (be it stackoverflow or a github repo) i am happy with the kotlin examples most of the time but always find myself heavily refactoring converted java samples. I know Java is very verbose by design, but even when using IntelliJ to convert the Java code to Kotlin I often find myself doing heavy refactoring. Everything is needlessly wrapped twice or thrice and the exception handling is completely overkill. is it convention in java to always write code that is very verbose not only syntax wise (which luckily the converter can get rid of) but also structure wise? example: I am currently looking into software testing and came accross assertions. Let's compare the implementations of
    assert()
    from the kotlin stdlib and
    assertEquals()
    from junit. the former is basically implemented as
    if (!condition)
        throw Exception(message)
    its as simple and intuitive as can be. meanwhile the implementation of the latter goes so far down the rabbit hole (I have to navigate through 4 different files for what is actually just 5 lines of code) that I'd have trouble understanding what the function even does if it wasn't for the descriptive name. And this isn't just some random snippet from a stranger on the internet, its one of the most popular testing frameworks out there. just why?? Edit: I don't just mean to vent, I mean this as an actual question. Why is this? There's gotta be a reason for it
    :kotlin: 4
    m
    a
    • 3
    • 6
  • j

    Jorge Castillo

    03/09/2020, 10:08 AM
    Hi! I’m exploring EduTools plugin trying to create a new course, but whenever I click on “Check” button to run a task the IDE goes like “No tests were found” error but the plugin reports a “✅ Correct”
    a
    • 2
    • 3
  • k

    Kenneth

    03/10/2020, 8:29 AM
    If I have a function that requires not null variables, what is the best way to null check them before calling the function?
    d
    e
    +4
    • 7
    • 8
  • t

    Tia Petts

    03/11/2020, 12:51 AM
    message has been deleted
    a
    • 2
    • 2
  • h

    hooliooo

    03/11/2020, 11:07 AM
    is there a way to compare elements to each other in a list? For example if I have:
    listOf(A, B, C)
    I want a way to compare A to B, B to C and A to C so they are all evaluated against each other
    ➿ 1
    s
    s
    +2
    • 5
    • 5
  • c

    Christian Sousa

    03/12/2020, 11:54 AM
    anyone can help me with my project? I’m trying to target ios9, but I cant seem to get it right using the build.gradle
    📱 1
    s
    • 2
    • 1
  • b

    Badecx

    03/13/2020, 1:26 PM
    any thoughts?
    a
    • 2
    • 1
  • b

    Badecx

    03/13/2020, 4:37 PM
    we decide to not use any of theses, we just name an interface as MyStuffInterface, then used it in the implementation. Tks for inputs ;D
    🙁 1
    k
    c
    • 3
    • 3
  • j

    JP

    03/14/2020, 12:43 PM
    Hi, can anyone explain why in this code:
    fun List<User>.aggregate(): List<User> {
        val result = this
            .groupingBy { it.login } // Grouping<User, String>
            .aggregate { key: String, accumulator: User?, element: User, first: Boolean
                ->
                if (first) element
                else User(
                    accumulator!!.login,
                    accumulator!!.contributions + element.contributions
                )
            }
        return result.values.toList()
    }
    result
    ’s type becomes
    Map<String, User?>
    , while I was expecting it to be
    Map<String, User>
    ?
    j
    • 2
    • 5
  • c

    chrisalbright

    03/16/2020, 8:41 PM
    I’ve got what may be an interop nightmare. I’m converting a Java library to Kotlin, and the library has a dependency on a different library implemented in Clojure. The Clojure library throws an IllegalStateException but the Kotlin re-write seems to completely discard that exception when thrown. Is this expected behavior in Kotlin? Is there a way to get the previously expected behavior back?
    m
    • 2
    • 2
  • h

    harry.singh

    03/17/2020, 11:08 PM
    Hi! Reading on smart cast in Kotlin and came up on following statement
    When you're using a smart cast with a property of a class, the property has to be a val and it can't have a custom accessor. Otherwise, it would not be possible to verify that every access to the property would return the same value.
    Makes sense but one thing that I don't understand is, what does the author mean
    property has to be a val and it can't have a custom accessor
    Doesn't val properties provide only getter methods?
    a
    q
    • 3
    • 5
Powered by Linen
Title
h

harry.singh

03/17/2020, 11:08 PM
Hi! Reading on smart cast in Kotlin and came up on following statement
When you're using a smart cast with a property of a class, the property has to be a val and it can't have a custom accessor. Otherwise, it would not be possible to verify that every access to the property would return the same value.
Makes sense but one thing that I don't understand is, what does the author mean
property has to be a val and it can't have a custom accessor
Doesn't val properties provide only getter methods?
a

araqnid

03/17/2020, 11:24 PM
it can’t be defined as
val someProperty get() = …
= custom accessor
h

harry.singh

03/18/2020, 12:08 AM
why defining it as
val someProperty get() = ...
fails to verify that the val was changed?
q

Quy D X Nguyen

03/18/2020, 12:15 AM
Because the getter could return different things depending on what the ... Is
a

araqnid

03/18/2020, 12:21 AM
e.g.
val someProperty: String? get() = if (System.currentTimeMillis % 2 == 0) "hello" else null
- the nullness-or-not is unpredictable
h

harry.singh

03/19/2020, 3:18 PM
Gotcha!
View count: 2