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

    benny.huo

    04/09/2020, 7:09 AM
    Hi, I find that this code generates 4 classes to represent ‘::x’, is it a bug? Thus making ‘::x === ::x’ equals false.
    fun main() {
        val a = ::x
        val b = ::x
        val c = ::x
        val d = ::x
    }
    
    fun x(){
    
    }
    t
    s
    +3
    • 6
    • 8
  • p

    Pascal How

    04/09/2020, 11:24 AM
    Hi, I really like
    buildList
    and I was wondering if there is a way to use it without having to write
    @ExperimentalStdlibApi
    everywhere.
    m
    l
    +2
    • 5
    • 6
  • a

    Antanas A.

    04/09/2020, 12:03 PM
    Hi, does any one thought about concept - "*Explicit Catch Exceptions*"? It would be a kind of exception which can be caught by specifying it explicitly try { } catch (e:ExceptionType) { } and impossible to catch in otheF ways. For e.g. this would solve problems with CancellationException propagation, using flow api. Currently there are cases where we need to explicitly catch and rethrow these "internal" exceptions and code is like: try {} catch (e:CancellationException) { throw e } catch(e:Exception) { } Usage would be annotate exception class with @ExplicitOnly annotation like this:
    @ExplicitOnly public expect open class CancellationException(message: String?) : IllegalStateException
    j
    d
    p
    • 4
    • 4
  • s

    spand

    04/09/2020, 1:38 PM
    In case anyone else missed it: https://youtrack.jetbrains.com/issue/KT-34743 🎊 Trailing commas !
    🎉 5
    :kotlin-flag: 2
    d
    s
    +2
    • 5
    • 5
  • a

    Ashish Kumar Joy

    04/09/2020, 2:54 PM
    Do we anything equilavent to scala fmt for Kotlin. https://scalameta.org/scalafmt/
    z
    m
    • 3
    • 4
  • s

    Sandy

    04/09/2020, 3:23 PM
    abstract class BaseEventConsumer<EV : TBase<EV, out TFieldIdEnum>, ID>(val topic: String) we are using kafka, and I don't understand the meaning of EV, EV: TBase<EV, out TFieldEnum> .
    s
    s
    • 3
    • 5
  • w

    WukongRework.exe

    04/09/2020, 8:51 PM
    is their a possible way to have an object deconstruct into a variable amount?
    c
    a
    • 3
    • 9
  • b

    bod

    04/10/2020, 11:50 AM
    Hello, World! Isn't there an equivalent of
    forEach
    on collections but with a lambda with the element as a receiver (instead of
    it
    )?
    j
    • 2
    • 2
  • j

    Joshua

    04/10/2020, 4:31 PM
    Can anyone tell why this works in Fragment A but not in Fragment B. Fragment A:
    viewModel.toolbarViewConfig.title.value = "What do you want to do?"
    Fragment B:
    activityViewModel.toolbarViewConfig.title.value = "Make $$$"
    More Code Fragment A:
    val viewModel = ViewModelProvider(activity!!)
        .get(MainActivityViewModel::class.java)
    
    viewModel.toolbarViewConfig.title.value = "What do you want to do?"
    viewModel.toolbarViewConfig.isMenuVisible.value = true
    
    
    return inflater.inflate(R.layout.fragment_home, container, false)
    More Code Fragment B:
    val viewModel = ViewModelProvider(this).get(GoOnlineViewModel::class.java)
    val activityViewModel = ViewModelProvider(activity!!).get(MainActivityViewModel::class.java)
    val binding = DataBindingUtil.inflate<FragmentSellerGoOnlineBinding>(
        inflater, R.layout.fragment_seller_go_online,
        container, false
    ).apply {
        this.lifecycleOwner = viewLifecycleOwner
        this.viewModel = viewModel}
    
    activityViewModel.toolbarViewConfig.title.value = "Make $$$"
    activityViewModel.toolbarViewConfig.isMenuVisible.value = false
    
    viewModel.navigationCommand.observe(viewLifecycleOwner, Observer {
        when(it) {
            is <http://NavigationCommand.To|NavigationCommand.To> ->
                Navigation.findNavController(requireView()).navigate(it.directions)
        }
    })
    
    
    
    return binding.root
    I'm not able to override the value
    viewModel.toolbarViewConfig.title.value
    in fragment B
    k
    • 2
    • 1
  • a

    Ananiya

    04/10/2020, 5:16 PM
    is kotlin future of android development
    z
    • 2
    • 5
  • y

    yodgor777

    04/10/2020, 7:14 PM
    I am having problem and getting some exceptions maybe some had the same problem I have posted my question to stackoverflow https://stackoverflow.com/questions/61139367/how-to-implement-room-database-with-coroutines-correctly?noredirect=1#comment108162167_61139367
    b
    • 2
    • 1
  • e

    Edoardo Luppi

    04/11/2020, 8:33 AM
    Anyone was able to setup CI with Github on a Kotlin repo?
    • 1
    • 1
  • v

    voben

    04/11/2020, 12:30 PM
    Is it best practice in kotlin to use imports with
    *
    or is it prefered to write out all import statements?
    l
    c
    • 3
    • 3
  • e

    Erik Dreyer

    04/11/2020, 3:19 PM
    Is it possible to leverage data classes while also ensuring they are created in a consistent state (e.g. by using a factory method)? After reading the following, it seems not, but I wanted to make sure: https://www.reddit.com/r/Kotlin/comments/78dl7m/data_class_factory_constructor_issue/
    o
    • 2
    • 4
  • a

    Abinandhan

    04/11/2020, 3:29 PM
    Post your answer and then try in Ide. If your answers match, kindly reason this, you are great😉 . I couldn't understand the working of this one
    k
    s
    o
    • 4
    • 21
  • c

    CLOVIS

    04/11/2020, 4:41 PM
    In Java, it is possible to declare an object of a type
    Something<?>
    to say that the generic is ignored. Is there any similar syntax in Kotlin? If so, where can I find documentation that explains how to use it?
    a
    s
    +2
    • 5
    • 5
  • o

    Ofir Bar

    04/11/2020, 7:45 PM
    Hey guys, I tried to read this block of code (from kotlin docs) a few times but I can't understand 3 things. 1. Red part- why is there a semicolon there? 2. Blue part - how is the
    parent
    which is a
    Person
    type can just call the
    children
    variable as like this list is a part of it? 3. I am also not sure how a
    Person
    instance is passed to the constructor of a class which is
    Person
    Source: https://kotlinlang.org/docs/reference/classes.html
    k
    d
    p
    • 4
    • 9
  • a

    Animesh Sahu

    04/12/2020, 12:11 PM
    is there a way to have extension function only applicable to sealed classes, like (pseudo):
    inline fun <reified T : Any> T.ext() "where T::class.isSealed" {}
    m
    z
    • 3
    • 2
  • l

    liminal

    04/12/2020, 4:44 PM
    enum class MyType { A, B, C }
    
    data class MyTypeWrapper(val id: String, val type: MyType)
    
    // existing code to order types based on some business rules
    fun mapToOrderedTypeList(unordered: List<MyType): List<MyType> { return ... }
    How do I order a list of `MyTypeWrapper`s based on order of their `type`s?
    r
    • 2
    • 2
  • j

    Joshua

    04/12/2020, 10:20 PM
    If anyone wants to give it a try. I have been scratching my head 4 days now. All kind of help would be appreciated. https://stackoverflow.com/questions/61178954/data-binding-behaving-unexpected-between-fragments-and-activity
    m
    • 2
    • 1
  • e

    Edoardo Luppi

    04/13/2020, 9:28 AM
    Morning 😄 Is there a way to get rid of these? A bit annoying
    w
    m
    t
    • 4
    • 11
  • m

    Michael de Kaste

    04/13/2020, 11:17 AM
    Did I encounter a bug? consider the following code:
    typealias Point = Pair<Int, Int>
    val (axis1, axis2, pointConstruct) = when(horizontal){
        true -> Triple(0..height, 0..width, {a1, a2 -> Point(a1, a2)})
        false -> Triple(0..width, 0..height, {a1, a2 -> Point(a2, a1)})
    }
    Instead of telling me:
    Type cannot be infered
    on a1,a2 in any of both lambdas, it simply states that Point is unreachable code. Alongside; it states that pointConstruct is a
    (Nothing, Nothing) -> Point
    function simply declaring:
    val pointConstruct = {a1, a2 -> Point(a1, a2)}
    will correctly tell me that a1 and a2 cannot be infered. Why does it infer a
    (Nothing, Nothing) -> Point
    in the deconstructed lamba, but a compile error on the single line one?
    k
    a
    • 3
    • 3
  • w

    wasyl

    04/13/2020, 11:27 AM
    Is there any way to turn on
    allWarningsAsErrors
    but allow deprecation warnings?
    allWarningsAsErrors
    is nice, but it prevents us from using
    @Deprecated
    annotation to provide seamless code migrations 😕
    a
    • 2
    • 3
  • m

    Mikael Alfredsson

    04/13/2020, 5:24 PM
    is there a reason behind the ‘eager’ evaluation of safecalls in kotlin?
    data class B(val i: Int)
    data class A(val b: B)
    
    class Test {
        var a: A? = A(B(1))
        fun get(): Int {
            return a?.b.i ?: -1
        }
    }
    the expression
    a?.b.i
    must in kotlin be written as
    a?.b?.i
    but in reality, if
    a
    isnt null, we know that
    b
    must contain
    i
    (in Swift i think the former expression is valid)
    r
    h
    • 3
    • 16
  • t

    Tmpod

    04/13/2020, 8:19 PM
    Hey! o/ I'm in need of making some archives and for the sake of "universality" I decided to go with ZIP, and so I'm wondering if there's any nicer way than Java's zip module 😅 Thanks in advance!
    g
    • 2
    • 10
  • e

    Enock Kalya

    04/14/2020, 5:55 AM
    hello everyone, I'm new to kotlin and I am looking for resources to help me practice..
    h
    • 2
    • 1
  • j

    Jaymin.Kim

    04/14/2020, 7:47 AM
    Is there any way to access base implementation of class delegation?
    interface Base { fun foo(): Int }
    object A {
        fun createBase(): Base =
            object : Base { override fun foo(): Int = 1 }
    }
    object B : Base by A.createBase() {
        override fun foo(): Int {
            // CANNOT access 'super', how to access instance created with 'createBase()' ?
            return super.foo() + 1
        }
    }
    d
    c
    • 3
    • 3
  • p

    Paul Woitaschek

    04/14/2020, 3:01 PM
    How can I suppress warnings about the opt in marks? I have allWarningsAsErrors enabled but now my build fails because I have opt in free compiler args applied on all modules and now it prints warnings on
    w: Opt-in requirement marker kotlinx.coroutines.FlowPreview is unresolved. Please make sure it's present in the module dependencies
    for example
    a
    • 2
    • 3
  • t

    tylerwilson

    04/14/2020, 3:46 PM
    I find it interesting that Android Studio tells me there is a 1.3.72 Kotlin release before I read anything about it here… 🙂
    ➕ 4
    m
    • 2
    • 1
  • o

    Ofir Bar

    04/14/2020, 5:34 PM
    The following structure is repeated in my code:
    val arrayList : ArrayList<String> = arrayListOf()
    for(person in 0..listOfPersonsIndex){
    arrayList.add(person[i])
    }
    I would like to no do that declaration of empty arraylist and the assign it. Is there a cleaner way to immediately assign a value for it in the stdlib?
    j
    o
    z
    • 4
    • 3
Powered by Linen
Title
o

Ofir Bar

04/14/2020, 5:34 PM
The following structure is repeated in my code:
val arrayList : ArrayList<String> = arrayListOf()
for(person in 0..listOfPersonsIndex){
arrayList.add(person[i])
}
I would like to no do that declaration of empty arraylist and the assign it. Is there a cleaner way to immediately assign a value for it in the stdlib?
j

jw

04/14/2020, 5:37 PM
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/build-list.html
👍 1
o

Orhan Tozan

04/14/2020, 6:04 PM
Is listOfPersonsIndex a List? If so,
listOfPersonsIndex.toList()
would be all you need.
☝️ 1
z

Zach Klippenstein (he/him) [MOD]

04/14/2020, 6:04 PM
also
List(n) { person[it] }
or best of all, just
person.toMutableList()
View count: 1