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

    Ashutosh Panda

    11/05/2019, 2:39 AM
    I want to declare an array but do not want to put values into it then itself I will enter values later when require , as it happens in other languages , however how should I do it in Kotlin
    m
    m
    b
    • 4
    • 10
  • j

    jmfayard

    11/05/2019, 10:43 AM
    I have colleagues that use
    .let { ... }
    all the time and don't really understand the need for the others. I know there are multiple articles on when to use
    let, also, with, apply, run, takeIf, ...
    But which one did you find the most useful?
    s
    m
    +5
    • 8
    • 26
  • e

    Exerosis

    11/05/2019, 1:30 PM
    Compound Extensions... will they exist at some point?
    m
    • 2
    • 2
  • e

    Exerosis

    11/05/2019, 1:33 PM
    there is some talk here... I totally need them... actually I simply want:
    interface SomethingWithEvents {
        fun Toggled.onSomething(listener: () -> (Unit))
    }
    To get called like this:
    fun main(args: Array<String>) {
        (args as Toggled).apply {
            val something = args as SomethingWithEvents
            something.onSomething {
                println("Come on Kotlin for real m8")
            }
        }
    }
    which would ultimately make a java call like this:
    something.onSomething(this, () -> {
    
    });
    d
    • 2
    • 7
  • v

    Vishnu Haridas

    11/05/2019, 2:24 PM
    How idiomatic is using an Immediately Invoked Function Expression (IIFE) with an Elvis after
    let
    ,
    also
    ,
    apply
    etc. to execute some code when the receiver is null? For example,
    val response = getFromUrl(...)
    
    response?.data?.user?.also {
        ...  // welcome the user, save data, and lot more.
    } ?: {
        showError("Login failed")
    } ()  // IIFE
    s
    p
    +3
    • 6
    • 13
  • i

    Iaroslav Postovalov

    11/05/2019, 5:13 PM
    Hey! Why does mutableMapOf return exactly LinkedHashMap, not a simple HashMap? upd.: I understand why mutableListOf returns ArrayList - it is the most frequently used implementation of MutableList... But why do we need LinkedHashMap? By what criterion is it better than plain HashMap?
    ➕ 6
    w
    t
    +2
    • 5
    • 5
  • r

    Robert Jaros

    11/05/2019, 7:17 PM
    Anyone knows a library which allows to send email from Kotlin/JVM app without blocking (coroutines? reactive?)
    f
    j
    • 3
    • 4
  • k

    Kroppeb

    11/05/2019, 11:39 PM
    IntelliJ suggests to convert
    r1
    to
    r2
    , but these are not equivalent. (The inferred type isn't even the same) Seems to be an issue if an extension function on a nullable type gives a generic type with the input type as one of the type parameters and as input a nullable type with a nullable parameter
    s
    f
    +3
    • 6
    • 9
  • m

    Mani

    11/06/2019, 10:06 AM
    val pickableState = try {
                PickableState.valueOf(state)
            } catch (ex: Exception){
                null
            }
    is there a better way to check if a string is present in ENUM?
    j
    m
    • 3
    • 4
  • j

    jeggy

    11/06/2019, 11:38 AM
    I have a big kotlin project that takes about 3-5 minutes to start up using the play button in IntelliJ. So now I wanted to know why it takes so long, so I tried the new Java Flight Recorder to figure what was wrong, and found that nothing was wrong and by using java flight recorder it actually started in 1-3 seconds and everything is working fine. Does anyone know what it could be that I'm doing wrong?
    t
    l
    • 3
    • 7
  • a

    AndreyVanDenHaag

    11/06/2019, 3:29 PM
    Hi all, I would like to try Ktor to implement a server for a TCP based protocol. All the documentation and examples are about HTTP. The only docs I could find is this: https://ktor.io/servers/raw-sockets.html Can anyone point me to a blog or a project to get more information how to implement non-HTTP protocol with Ktor ?
    f
    r
    m
    • 4
    • 8
  • a

    alex

    11/06/2019, 11:07 PM
    Right now I'm getting
    ClassCastException
    and debugging shows that
    line no. 12
    does nothing. What might be the reason, that
    inline
    version sometimes (for some calls) skips the cast and returns the same object (i.e.
    String
    ) instead of
    reified T
    ? Classic approach with passing class ref works fine.
    Untitled
    q
    • 2
    • 7
  • r

    Raymond Barlow

    11/07/2019, 4:41 AM
    is there a `const()`funciton in Kotlin? (or equivalent)
    b
    k
    m
    • 4
    • 18
  • v

    vineethraj49

    11/07/2019, 6:08 AM
    does
    !==
    just translate to
    !  ==
    which is
    !=
    ?
    j
    • 2
    • 1
  • r

    Roberto Messina

    11/07/2019, 9:23 AM
    How can i clear intellij console by kotlin?
    m
    • 2
    • 1
  • o

    Oleh Ponomarenko

    11/07/2019, 11:25 AM
    How can I transalte this to Kotlin from Java:
    while ((inputLine = input.readLine()) != null) {
    Log.d(TAG, inputLine);
       }
    d
    s
    p
    • 4
    • 6
  • j

    Jakub Begera

    11/07/2019, 11:47 AM
    Hello, I’m dealing with following issue with Kotlin/Java Compiler. Imagine following scenario: let
    First
    be a Java class with a final function and
    Second
    be a Kotlin class extending
    First
    with a function of the same name like the final function in
    First
    class, i. e.:
    // Java class
    class Firs {
        final void foo() { }
    }
    // Kotlin class
    class Second: First() {
        fun foo() { }
    }
    Obviously, it’s wrong because the final function
    foo()
    can not be overridden. However, compilation pass successfully and in run-time I get
    java.lang.LinkageError: Method void Second.foo() overrides final method in class First
    . Is this correct behavior of compiler? I supposed that there will be some validations for this case. Thank you! 🙂
    😬 2
    :yes: 1
    m
    • 2
    • 1
  • l

    LeoColman

    11/07/2019, 3:35 PM
    But I don't really want to, I want it to cast everything to Any if the user doesn't provide the value
    r
    c
    s
    • 4
    • 23
  • e

    Ellen Spertus

    11/07/2019, 8:20 PM
    How would I fix this code? I’d like
    reportError()
    to be called if the value preceding
    let
    is `null`:
    store.state.selectedTab?.content?.url.let {
         doSomething(it)
     } ?: run {
         reportError("Unable to get URL to send")
     }
    Assume that both
    doSomething()
    and
    reportError()
    are void.
    s
    a
    +4
    • 7
    • 18
  • b

    Brian Norman

    11/08/2019, 1:15 AM
    In Kotlin how do you test equivalence between two Lists? i.e content is the same but not necessarily the same order?
    d
    c
    +2
    • 5
    • 7
  • a

    Antonio Aradaza

    11/08/2019, 1:38 AM
    Hello, how to call a function at the start of application then stop it immediately? Like "one-time" use only
    a
    s
    • 3
    • 2
  • j

    John

    11/08/2019, 12:14 PM
    Other than making it "work" with vararg that is
    b
    • 2
    • 2
  • n

    nimtiazm

    11/08/2019, 8:41 PM
    In multiline string, is there a way to add newline in literal but not in string itself? I realize it’s possible to do
    """ …\n """.replace("\n", "")
    but i’m looking for a better way
    s
    r
    b
    • 4
    • 8
  • h

    Hullaballoonatic

    11/09/2019, 5:01 AM
    What is the point of
    ByteArray
    ,
    IntArray
    ,
    CharArray
    etc? why not just
    Array<Byte>
    ,
    Array<Int>
    ,
    Array<Char>
    . I know that Java does treat primitive arrays differently from object arrays, but couldn't Kotlin do us a solid and smoosh them all into just
    Array<T>
    ?
    d
    g
    • 3
    • 6
  • v

    ventura

    11/09/2019, 10:39 AM
    I am trying to create scaffolding script for creating Ktor apps from CLI (like Django, Rails, etc). Should I use Yeoman (i.e. write in JavaScript) or is there a more Kotlin-way of doing it?
    j
    • 2
    • 1
  • h

    hellman

    11/09/2019, 4:05 PM
    I got this at the moment, but that doesn’t work:
    plugins {
        id("org.jetbrains.kotlin.js") version "1.3.60-eap-76"
    }
    
    repositories {
        mavenCentral()
        mavenLocal()
        maven(url = "<https://dl.bintray.com/kotlin/kotlin-eap>")
    }
    o
    m
    • 3
    • 11
  • w

    william

    11/10/2019, 3:57 AM
    since there are no checked exceptions in kotlin, is it best to have error return values instead?
    s
    s
    +2
    • 5
    • 5
  • t

    Travis Griggs

    11/10/2019, 5:13 AM
    I have a typealias for UInt (
    typealias PlanOID = UInt
    ). Ideally, I’d like to bind a class/type/static function to PlanOID (e.g.
    PlanOID.nowOID()
    ), but I think this is not possible. I’m assuming that PlanOID is just what it says, a substitution alias, not a distinct type. And since UInt doesn’t have a Companion, I can’t extend that. Is this correct? Am I missing some other trick. I get that I can just define a global free function, but I’d rather bind the behavior to the type if I could (avoids namespace clutter)
    w
    • 2
    • 2
  • m

    Marcin Wisniowski

    11/10/2019, 11:49 AM
    Does anyone have an idiomatic way of checking if the last
    n
    elements of a list are the same? Currently I have
    list.takeLast(n).toSet().size == 1
    but I think this could be simpler.
    k
    m
    +4
    • 7
    • 12
  • z

    zceejkr

    11/10/2019, 4:34 PM
    Hi, one question if I may: I have a sealed class Foo that is extended by A, B and C and a generic interface Bar<T>. Bar only requires one method that returns T. I want to make an object of type Bar<Foo>, that will return one of the Foo members. But if I put the type Bar<Foo> and try to return A in the required method, I get a type error (it wants Foo, not A). If I put the type Bar<out Foo>, i get this error:
    Projections are not allowed for immediate arguments of a supertype
    . I am new to generics so if anyone can point me in the right direction I would be thankful.
    s
    k
    • 3
    • 4
Powered by Linen
Title
z

zceejkr

11/10/2019, 4:34 PM
Hi, one question if I may: I have a sealed class Foo that is extended by A, B and C and a generic interface Bar<T>. Bar only requires one method that returns T. I want to make an object of type Bar<Foo>, that will return one of the Foo members. But if I put the type Bar<Foo> and try to return A in the required method, I get a type error (it wants Foo, not A). If I put the type Bar<out Foo>, i get this error:
Projections are not allowed for immediate arguments of a supertype
. I am new to generics so if anyone can point me in the right direction I would be thankful.
s

streetsofboston

11/10/2019, 4:38 PM
Did you try to declare Bar as follows, with a covariant generic param
T
(out on the declaration site):
interface Bar<out T> { fun oneMethodThatReturnsT(): T }
?
Also, if you could provide a snippet of the code that doesn’t compile would really help 🙂
z

zceejkr

11/10/2019, 6:17 PM
Ok so I have done so and it works now (on JVM). But the same code does not work when compiled to JavaScript. Not a compile time error, it does not work at runtime. The example is somewhat convoluted and I think it might be a bug with kotlinc-js. Do you know where I could report such a bug?
k

karelpeeters

11/10/2019, 7:21 PM
https://youtrack.jetbrains.com/oauth?state=%2Fissues%2FKT
👍 1
View count: 1