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

    miqbaldc

    08/25/2019, 2:30 PM
    How to use function overload for list of data type? e.g:
    fun fun1(list: List<DataA>)
    
    fun fun1(list: List<DataB>)
    The current condition declaration was clashed. any workaround? 1. I've tried to use
    typealiases
    but it still clashed. e.g: typealias ListDataA = List<DataA> 2. Using extensions function, still clashed. e.g: ListDataA.fun1()
    s
    j
    • 3
    • 3
  • f

    Florian

    08/26/2019, 10:59 AM
    when
    doesn't have a short form for
    !=
    right?
    k
    k
    • 3
    • 6
  • a

    Aslam Hossin

    08/28/2019, 2:46 AM
    How to use the method option
    Int
    optional parameter?
    f
    m
    • 3
    • 3
  • a

    am

    08/28/2019, 9:30 AM
    Is it good way to define constants as a top level declaration with
    internal
    key word eg
    internal const NAME_FOO:String = " "
    class Foo{
    }
    a
    t
    • 3
    • 4
  • f

    Florian

    08/28/2019, 9:53 AM
    Is there is specific reason that
    <
    etc are not supported in
    when
    (I mean in the same way as
    in
    and
    is
    )
    l
    m
    • 3
    • 3
  • f

    Florian

    08/29/2019, 1:29 PM
    Can I use any data type in a
    when
    statement?
    :yes: 3
    m
    k
    +2
    • 5
    • 20
  • m

    matt tighe

    08/29/2019, 6:07 PM
    i’ve tried to set up a sealed class that extends an interface in order to get compile-time exhaustiveness, but it doesn’t work the way i wanted it to.
    interface ErrorField
    data class InputError(
        val field: ErrorField
        val message: String
    )
    
    // elsewhere
    internal sealed class Field : ErrorField {
        object MyField : Field()
    }
    
    // complains about exhaustiveness
    return when (error.field) {
        is Field.MyField -> {}
    }
    is there a way to get the behavior i’m looking for? that is, to have a generally defined type but have the exhaustiveness check be aware that the subtype is actually exhausted?
    t
    • 2
    • 15
  • f

    Florian

    08/30/2019, 8:36 AM
    When I have
    when
    without an argument and I want to put 2 cases into 1 branch I have to divide them with || , right?
    s
    k
    a
    • 4
    • 5
  • m

    matt tighe

    08/30/2019, 8:58 PM
    is there a way to design a generic contract that will be implemented using internal types? i.e:
    interface Entity
    internal class MyClassEntity : Entity {}
    
    interface Model
    class MyClass {} : Model
    
    interface Repository<M: Model, E: Entity> {
        fun constructEntity(model: M): E
    }
    basically I want to expose
    MyClass
    and implementations of
    Repository
    , but I want some way to construct entities internally and still have them be part of a contract
    t
    • 2
    • 1
  • f

    Florian

    08/31/2019, 8:30 PM
    I often see people write that
    when
    without an argument is a replacement for an
    if-else-if
    ladder. But why particularly the argument-less one? Isn't it also a replacement for
    if-else-if
    when it has an argument?
    s
    m
    • 3
    • 7
  • u

    ursus

    09/01/2019, 5:28 AM
    having else with return false everywhere is ugly
    p
    s
    • 3
    • 6
  • l

    LastExceed

    09/03/2019, 3:29 AM
    fun Foo(x: Float?): Boolean {
        var result = false
        if (x != null) {
            result = x > 1f
        }
        return result
    }
    can this be simplified? maybe using elvis operator somehow?
    s
    r
    +3
    • 6
    • 5
  • h

    hooliooo

    09/03/2019, 6:35 AM
    Hi guys, is there documentation about the higher order functions in collections that show the complexity like O(1) / O(n) etc.?
    k
    • 2
    • 1
  • m

    Marko Mitic

    09/03/2019, 11:06 AM
    I have this inline reified function, is there a way for compiler to optimize away when branches other than the matching one (considering it's inline)
    suspend inline fun <reified T> get(key: String): T? =
            dao.getById(key)?.let {
                when (T::class) {
                    String::class -> it.value as T
                    Int::class -> it.value.toInt() as T
                    Float::class -> it.value.toFloat() as T
                    Double::class -> it.value.toDouble() as T
                    else -> throw IllegalArgumentException("Not implemented for the given type.")
                }
            }
    s
    e
    • 3
    • 6
  • s

    sandi

    09/04/2019, 4:22 PM
    data class User(val name: String, val email: String)
    
    val user: User get() = User(email = getEmail(), name = getName())
    What is the order of execution here? Do named arguments get resolved (1) according to the data class argument positioning or (2) when creating the object with named arguments?
    d
    l
    +2
    • 5
    • 12
  • m

    mathew murphy

    09/04/2019, 6:34 PM
    Is there a standard interface for "class which implements toString()"? Like
    Stringer
    in Go?
    r
    t
    m
    • 4
    • 4
  • m

    mathew murphy

    09/04/2019, 6:35 PM
    Yes. I guess I'll have to define some other interface, or else Any will be acceptable.
    m
    • 2
    • 1
  • j

    Johan Alkstål

    09/07/2019, 8:59 PM
    Or its methods
    k
    m
    • 3
    • 4
  • m

    Morgan

    09/07/2019, 9:07 PM
    Hello all. Looking to learn a little bit of Kotlin for Android. No serious Java experience outside of some Java for idiots type stuff back in the Java 6 days (or around then). I do have some programming experience in C and C++ (with Qt), Python and Swift but only hobby stuff tbh. Just wondering where the “best” place to start for someone like me is? Not a total newb to programming but not a professional by any means. Books, courses, videos, etc. I am on a Mac (Mojave) if that matters. Thanks!
    j
    j
    d
    • 4
    • 13
  • j

    Johan Alkstål

    09/09/2019, 2:24 PM
    Could someone explain to me what the deal is with JDK versions? 11 is the latest but 8 seems to be mostly used. One is going to be managed by OpenJDK and the other by OracleJDK? Are there licensing differences as well? Should 8 be used when starting fresh?
    s
    o
    +2
    • 5
    • 34
  • j

    Johan Alkstål

    09/09/2019, 2:45 PM
    What's the difference between mavenCentral and jCenter?
    m
    m
    +2
    • 5
    • 9
  • d

    Donal

    09/10/2019, 8:42 AM
    I’m looking for a Kotlin console or REPL (similar to the Groovy console) i.e. - a GUI that allows you to type multiple statements - when the statements are executed, the result of the last expression (or an error) is shown Does such a thing exist? I have the ultimate edition of IntelliJ if there’s a plugin that provides this functionality.
    a
    u
    • 3
    • 3
  • r

    RoqueRueda

    09/10/2019, 2:13 PM
    Hi guys, so I have a question regarding lambdas: I have a function like:
    fun addVisibilityListener(listener: (Int) -> Unit = {})
    I want to create a list of listeners, It is possible to have a list of lambdas? or how can I handle that scenario?
    a
    m
    • 3
    • 3
  • d

    david-wg2

    09/10/2019, 2:22 PM
    can anyone think of an elegant way of getting the tag-name of a html-tag? currently i have
    "<my-tag>...</my-tag>".removePrefix("<").takeWhile { it != '>' }
    s
    m
    a
    • 4
    • 9
  • a

    Akhil Suseelan

    09/10/2019, 3:37 PM
    Hi guys, I've a question: I want to convert a string(say, origin_source = sources) to mutableMap. How to implement with
    associateTo
    ?
    s
    d
    +2
    • 5
    • 7
  • j

    jk2018

    09/11/2019, 4:38 PM
    What's the best way to use a java class, but make it NonNullable? Wrap it in an inline class? Or is there an easier way? I basically would like to have a kotlin equivalent to a java class (which I can't change)
    m
    • 2
    • 2
  • a

    Andrew Walker

    09/11/2019, 5:13 PM
    #getting-started I'm new to Kotlin. Just finished Coursera course on Kotlin and looking for the next steps to learn. Are there good books or resources showing how to use Kotlin for Android development and for Android game development? I saw "Kotlin In Action" that is authored by the instructors of the Coursera course. BUT, it doesn't mention Kotlin development for Android and it's a bit old (aside: is a new edition about to come out?). My day job is desktop C# apps. I did some Android development >5 years ago in JAVA but it's a distant memory. Thanks!
    s
    r
    • 3
    • 6
  • e

    Emilio

    09/11/2019, 7:26 PM
    I'm trying to create some sort of compute graph and I'm trying to make my nodes a sealed class to exhaustively match on them with
    when
    . So I have something like (class internals omitted)
    sealed class Node
    sealed class SourceNode : Node() // No parents
    sealed class SinkNode : Node() // No children
    sealed class OpNode : Node()
    // classes that extend the sealed classes here
    I would like to distinguish at the type level nodes that have parents and nodes that have children so I could write something like:
    fun foo(x: ParentNode): ParentNode {
        // Do something to only parent nodes, possibly exhaustively match on them, and return a ParentNode
    }
    Where
    ParentNode
    is somehow a subtype of
    Node
    The problem is
    OpNode
    is both a parent node and a child node which calls for multiple inheritance via interfaces, but I would like to be within the land of sealed classes for exhaustive matching. Is there a solution to this in kotlin?
    b
    r
    • 3
    • 32
  • j

    Johan Alkstål

    09/11/2019, 7:43 PM
    If I have classes that implement interface
    Foo
    , when making a
    List<Foo>
    should be possible without casting the classes to their interface type? When I do
    fun listOfFoos(): List<Foo> {
        return listOf(
            FooA(),
            FooB(),
            FooC()
        )
    }
    it complains that each class is not a
    Foo
    but a
    FooA
    FooB
    and
    FooC
    . I would have thought that since they all implement the interface
    Foo
    it would just work?
    r
    • 2
    • 3
  • f

    Florian

    09/12/2019, 7:27 AM
    Is
    Unit
    the equivalent of Java's
    Void
    rather than lowercase
    void
    ?
    s
    k
    +2
    • 5
    • 21
Powered by Linen
Title
f

Florian

09/12/2019, 7:27 AM
Is
Unit
the equivalent of Java's
Void
rather than lowercase
void
?
s

spand

09/12/2019, 7:28 AM
It serves as both
k

karelpeeters

09/12/2019, 7:29 AM
Kind of, Java
Void
doesn't have an instance but it allows
null
so that's kind of the single instance.
l

Luca Nicoletti

09/12/2019, 7:31 AM
https://proandroiddev.com/kotlin-pearls-7-unit-nothing-any-and-null-cbbbbca86c2d
r

Ruckus

09/12/2019, 1:36 PM
Technically,
Void
id equivalent to Kotlin's
Nothing?
l

Luca Nicoletti

09/12/2019, 3:54 PM
I think it’s the equivalent for kotlin’s
Void?
a function which return
Nothing
can’t return, only throws or keep working
r

Ruckus

09/12/2019, 4:01 PM
Kotlin doesn't have
Void
, that's from java.
Nothing
can't return, but
Nothing?
can return only
null
, just like Java's
Void
.
l

Luca Nicoletti

09/12/2019, 4:02 PM
Sorry, meant
Unit?
r

Ruckus

09/12/2019, 4:02 PM
Unit?
can return
Unit
or
null
l

Luca Nicoletti

09/12/2019, 4:03 PM
Unit
is mapped to
Void
in Java
r

Ruckus

09/12/2019, 4:05 PM
No,
Unit
is mapped to
void
(lowercase) for return type in Java, but stays as
Unit
in other circumstances, such as generics.
l

Luca Nicoletti

09/12/2019, 4:06 PM
Yep, and what
Unit?
is mapped to?
r

Ruckus

09/12/2019, 4:06 PM
It will stay
Unit?
l

Luca Nicoletti

09/12/2019, 4:07 PM
into Java code
r

Ruckus

09/12/2019, 4:07 PM
Yes
l

Luca Nicoletti

09/12/2019, 4:07 PM
there’s not
Unit?
in Java…..
r

Ruckus

09/12/2019, 4:10 PM
Sorry, It would just be
Unit
, but with Java;s implied nullability.
l

Luca Nicoletti

09/12/2019, 4:10 PM
Got it 🙂
Thanks
r

Ruckus

09/12/2019, 4:11 PM
You can try it:
// Test.kt
fun test(): Unit? {
    return null
}

// Test.java
TestKt.test();  // returns kotlin.Unit
l

Luca Nicoletti

09/12/2019, 4:12 PM
Thanks 🙂
👍 1
View count: 3