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

    Slackbot

    02/04/2019, 4:48 PM
    This message was deleted.
    s
    • 2
    • 2
  • o

    oday

    02/05/2019, 10:29 AM
    i feel stupid
    j
    m
    • 3
    • 6
  • o

    otakusenpai

    02/05/2019, 1:57 PM
    Hello, I've a piece of function which does the following:
    inline fun letterInRange(char: Char): Boolean = char.compareTo('a')  || char.compareTo('b') ||
                                                       char.compareTo('c') || char.compareTo('d') ||
                                                       char.compareTo('e') || char.compareTo('f') ||
                                                       char.compareTo('g') || char.compareTo('h')
    Is there a way to shorten the function a bit more? I mean there are too many cases(and yes its giving an error too....)
    s
    r
    +5
    • 8
    • 21
  • o

    otakusenpai

    02/06/2019, 3:38 PM
    Hello people! Our teacher will ask us for a ML project in our next lab class. For this he has suggested using the python language along with Anaconda. I want to ask is is there any good machine learning platform for Java/Kotlin which is stable now? I know there is Tensorflow but the docs for Java are non existant.
    d
    r
    +2
    • 5
    • 6
  • s

    stephan_marshay

    02/06/2019, 11:28 PM
    return foo?.let { doStuff(it, bar, baz) } ?: false
    🙌 2
    s
    a
    • 3
    • 3
  • o

    oday

    02/07/2019, 2:11 PM
    I think like this
    saleCars.sortedWith(compareBy(nullsLast<Double>()) { it.hot_deal_likelihood })
    d
    k
    d
    • 4
    • 11
  • p

    Polina

    02/08/2019, 8:43 AM
    Hello! I had a question about file naming convention for file which contains multiple classes or only top-level declarations. https://kotlinlang.org/docs/reference/coding-conventions.html#source-file-names - use name with a upper first letter, but https://github.com/JetBrains/kotlin - use name with a lower first letter. What would be better? I prefer second way, but in little confuse why official kotlin github no follow official kotlin convention
    h
    a
    m
    • 4
    • 7
  • k

    Kevin

    02/08/2019, 11:13 PM
    I have a function that takes the following as a parameter:
    validator: ValidationContext.(String?) -> ValidationMessage?
    So I think I need to provide a function that takes in a
    ValidationContext
    and gives out a
    ValidationMessage
    , but what is up with the
    .(String?)
    . I don’t understand what the signature of my function should be.
    k
    k
    • 3
    • 7
  • k

    Kevin

    02/09/2019, 1:09 AM
    I want to validate a filepath to a sqlite database and provide helpful feedback, is this an appropriate way to accomplish this?
    return when {
        filename.isNullOrBlank() -> context.error("Cannot be blank")
        !File(filename).exists() -> context.error("File does not exist")
        !File(filename).isFile -> context.error("Not a file")
        !File(filename).canRead() -> context.error("Permission Denied")
        else -> when (val code = canConnect(filename)) {
            SQLiteErrorCode.SQLITE_OK -> context.success()
            else -> context.error(code.message)
        }
    }
    I only want to try to open a JDBC connection once I know it’s a valid filepath and all that, but is nesting a
    when
    inside the
    else
    of another
    when
    bad form?
    k
    • 2
    • 1
  • s

    Shane Blackburn

    02/10/2019, 2:00 PM
    Hey all! My name is Shane and I am very new to programming. Over the past month or so I have been learning Swift/Xcode for iOS development (it seemed like the simpler route to go for a complete beginner). But at heart I'm still an Android guy. Wondering if there are any good Kotlin tutorials or resources where I can learn Kotlin and then Android without prior Java knowledge. I plan to learn Kotlin/Android to get started and then learn Java as I need to to read old code bases for a job, etc. Thanks!
    👋 1
    a
    o
    • 3
    • 3
  • z

    ZargorNET

    02/11/2019, 3:28 PM
    Hey, I have a question to the coroutines in Kotlin: I want to implement a rate-limit http client which waits until the rate-limit expired and then goes on with the requests until the limit is exceeded again. My idea is to do this with callback functions. Like this:
    kotlin
       private val queue: Deque<() -> Unit> = LinkedList()
    
        fun addJob(req: String, callback: (String) -> Unit) {
            this.queue.offer {
                callback(req)
            }
        }
    
        //WILL RUN LATER AT AN UNSPECIFIED POINT OF TIME
        fun pullJob() {
            val func = this.queue.poll()
            if (func != null)
                func()
        }
    But I understood suspended functions in such way that they're there to get rid of the callbacks. So can I beautify this code with suspended functions? If so, how?
    m
    n
    • 3
    • 23
  • k

    Kenneth

    02/12/2019, 11:51 AM
    With a Map of <String, Int>, is there an elegant way to increment the Int if present, or set it to 0 if not?
    t
    s
    • 3
    • 2
  • o

    Oleh Ponomarenko

    02/12/2019, 1:13 PM
    How can I use a keyword "break" in foreach ? In Java I have this
    for (it in this.list) {
                    if (it == example) {
                        //do smth
                        break
                    }
                }
    In Kotlin I use:
    this.list.foreach{
        if(it==example) //do smth
    }
    I can't use "break" in foreach. I get an error: "Break & continue is only allowed inside a loop".
    m
    u
    +4
    • 7
    • 21
  • d

    dG

    02/13/2019, 10:41 AM
    data class Foo(
       val bar : Baz
    )
    data class Baz(
       val smth : String
       val zzz : String?
    )
    How would I enforce
    zzz
    not to be null in Foo (and in Foo only)? Can I achieve a non-nullable
    zzz
    there?
    d
    n
    • 3
    • 5
  • g

    Guru

    02/13/2019, 11:14 AM
    Dose anyone know how to use kotlinx.coroutines.* in terminal with simple GlobalScope.launch{..}
    m
    • 2
    • 2
  • g

    guppyfaced

    02/13/2019, 4:46 PM
    This is the bare bones version of an abstract factory I've designed from scratch. Is there a more idiomatic or efficient way of doing this?
    Design_Pattern__Abstract_Factory.kt
    k
    • 2
    • 4
  • d

    dave08

    02/13/2019, 4:52 PM
    Any ideomatic way of inserting a String at a specific position in another string?
    k
    s
    • 3
    • 11
  • j

    Jagdish

    02/14/2019, 9:40 AM
    Hello, Is it possible to start android development in kotlin without knowing Java ?
    r
    d
    s
    • 4
    • 3
  • p

    Paul N

    02/16/2019, 10:38 PM
    Just a quick coroutine question. All I want to do is fire off a large number of calculations in the background, and wait for them to finish before continuing. I'm not interested in any results from them. How do I wait for all of them to finish ?
    d
    • 2
    • 5
  • j

    Jubin Kuriakose

    02/17/2019, 3:04 PM
    Hi All, what is a good opensource project to get my hands dirty with Kotlin
    s
    • 2
    • 2
  • r

    Robert Jaros

    02/17/2019, 3:31 PM
    Feel free to play with my KVision project 😉
    🙂 1
    👍 1
    j
    • 2
    • 6
  • s

    snowe

    02/17/2019, 7:36 PM
    My pretty-print project is only one (prod) file, but shows many many elements of the language.. https://github.com/snowe2010/pretty-print
    j
    • 2
    • 3
  • o

    oday

    02/18/2019, 1:34 PM
    if requirementsAndInfo.key is nullable, that check inside the if is not sufficient to convince the parser that I did in fact check for nullability
    a
    j
    s
    • 4
    • 10
  • k

    Kevin

    02/19/2019, 9:04 PM
    I have a question about style. I have the following:
    data class Attachment(val filename: String?, val mimeType: String?)
    
    val Attachment.isImage: Boolean
        get() = this.mimeType?.contains("image") == true
    
    fun Attachment.load(): Image { ... }
    I want to keep my data classes as pure and simple as possible, and those extensions are just convenience methods for my UI and not core to the model. But I’m wondering if I should just define those things in the class itself?
    s
    k
    +2
    • 5
    • 8
  • t

    tohu

    02/20/2019, 11:31 AM
    What does everyone think about using
    require
    and
    check
    ? I find them useful especially for testing but I'm wondering if those checks should be removed in production.
    s
    • 2
    • 1
  • o

    Oleh Ponomarenko

    02/20/2019, 3:35 PM
    How can I insert (not replace) a byte at zero index in ByteArray ?
    d
    d
    • 3
    • 3
  • k

    Kenneth

    02/20/2019, 10:59 PM
    Regex("""^[\d]{9}$""")
    or
    Regex("""^[\d]{9}${'$'}""")
    ?
    g
    n
    • 3
    • 3
  • j

    jurajsolarml

    02/22/2019, 11:32 AM
    Hello,Please can you help me ? I am beginner. Where can be a bug ? /Kotlin 1.3.21,AS 3.5 Canary 5 / I tried to change Gradle version current 5.2.1 and Invalidate Caches/Restart and offline mode did not help. Thanks https://hastebin.com/zeyovujumu.shell https://hastebin.com/umowehuqew.xml https://hastebin.com/gixuvicabe.cpp
    h
    c
    +2
    • 5
    • 19
  • d

    dG

    02/22/2019, 12:40 PM
    val foo : SomeInterface = inputVariable
    val bar = if (foo is implA) (foo as implA) else (foo as implB)
    Here
    bar
    will be of type SomeInterface. Is it possible to somehow use implementation specific stuff available on both implementations but not on the interface, so
    bar.fieldOnlyOnImplementations
    ?
    d
    u
    h
    • 4
    • 3
  • h

    harry.singh

    02/23/2019, 8:20 AM
    var immutableList = listOf(1, 2, 3)
    
    immutableList += 4
    Since
    plusAssign
    operator is not defined on a
    Collection
    in Kotlin, what does
    immutableList += 4
    really do. It can't add the element to the the
    List
    as it is immutable unlike
    ArrayList
    . So does it first create a new
    List
    from the
    plus
    operator and then assign it to the reference variable through
    =
    ?
    r
    k
    • 3
    • 10
Powered by Linen
Title
h

harry.singh

02/23/2019, 8:20 AM
var immutableList = listOf(1, 2, 3)

immutableList += 4
Since
plusAssign
operator is not defined on a
Collection
in Kotlin, what does
immutableList += 4
really do. It can't add the element to the the
List
as it is immutable unlike
ArrayList
. So does it first create a new
List
from the
plus
operator and then assign it to the reference variable through
=
?
r

Ruckus

02/23/2019, 8:23 AM
Yes, this one does not use operator overloading, so it is interpreted literally as
immutableList = immutableList + 4
Note that if this was a mutable list, you'd get an error from ambiguity.
h

harry.singh

02/23/2019, 8:46 AM
yep because both
mutableList = mutableList + 4
and
mutableList.plusAssign(4)
would be applicable in this case and hence compiler will generate an error for the ambiguity
right?
r

Ruckus

02/23/2019, 8:47 AM
Exactly
👍 1
k

karelpeeters

02/23/2019, 8:51 AM
It does still use operator overloading of course 😉
h

harry.singh

02/23/2019, 9:29 AM
@karelpeeters you are referring to the
+
in immutable list example right?
k

karelpeeters

02/23/2019, 9:30 AM
Yes.
h

harry.singh

02/23/2019, 9:30 AM
Also if there was no
plus
operator defined on
List
, we would never get compiler error in the case of mutable list for
+=
right?
k

karelpeeters

02/23/2019, 9:37 AM
Yep.
r

Ruckus

02/23/2019, 3:25 PM
@karelpeeters Fair point 🙂
View count: 4