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

    jw

    02/25/2019, 5:01 PM
    if you can re-use, you should. avoid the repeated lookup
    c
    • 2
    • 1
  • s

    streetsofboston

    02/25/2019, 9:26 PM
    When to use
    when
    with
    or `run`… not sure… a matter of taste, in my opinion 🙂
    g
    • 2
    • 2
  • l

    liminal

    02/26/2019, 2:35 AM
    hi all, is there a performance hit when method reference is used vs lambda?
    a
    d
    p
    • 4
    • 5
  • j

    Jeremy

    02/26/2019, 9:02 AM
    Hello, I’m new in kotlin. Is there anyone who knows Scala language? I wanna convert from a code written Scala to kotlin. I don’t have knowledges related bounded type. For example this is a code written Scala language.
    // scala
    sealed trait Test[+A] {
       …
       def test[B >: A]: B
       …
    }
    
    // kotlin
    Sealed class Test<out A> {
       …
       fun <A : B> test(): B.   // <— this is problem
       …
    }
    I want to make type B is a super type of A. Anyone who knows this problem??
    r
    • 2
    • 2
  • e

    edwardwongtl

    02/26/2019, 9:22 AM
    try
    fun <A, B> test(): B where A: B
    j
    • 2
    • 1
  • j

    Jeremy

    02/26/2019, 9:34 AM
    So.. is there any other solution ?
    p
    r
    • 3
    • 7
  • n

    natpryce

    02/26/2019, 11:16 AM
    However, I still cannot get that example to compile when converted to Kotlin syntax. Seems to be a limitation of either the Kotlin type inference algorithm, or (more likely) my ability to bend it to my will.
    j
    r
    +2
    • 5
    • 17
  • r

    Rob

    02/26/2019, 2:13 PM
    is there a better way to have each subclass call the superclasses toString method without having
    override fun toString(): String {
        return super.toString()
    }
    in each of the subclasses?
    d
    s
    +2
    • 5
    • 11
  • k

    karelpeeters

    02/26/2019, 3:46 PM
    There's
    Pair
    and
    Triple
    , but I'm curious about what you mean by "bulky".
    data class Point(val x: Int, val y: Int)
    isn't a lot of code.
    ➕ 3
    n
    • 2
    • 1
  • j

    Joe

    02/26/2019, 5:38 PM
    I have a few generic `Map`s of String->Predicate functions of different types. eg, a
    Map<String, (Int)->Boolean>
    and a
    Map<String, (String)->Boolean>
    . I'd like to combine them to get a
    Map<String, (Any)->Boolean>
    , but can't quite figure out how to do so safely. I can safely cast to
    Map<String, *>
    or
    Map<String, Any?>
    without an unchecked cast warning, but I can't safely cast to `Map<String, (*)->Boolean>`(compile error) or
    Map<String, (Any?)->Boolean>
    (unchecked cast)
    r
    r
    • 3
    • 7
  • a

    awzurn

    02/27/2019, 12:18 AM
    Has anyone else run into a use-case of wanting to be able to copy a data class with a generic field, where the new value being provided (for the generic field) is a different type? I recently ran into when I was using a data class as a message wrapper for a parsed message (which included both the parsed typed entity and the payload it was parsed from). Scala support something like this with their `case class`:
    scala> case class Something[T](something: T)
    defined class Something
    
    scala> Something(1)
    res0: Something[Int] = Something(1)
    
    scala> res0.copy(something = "something")
    res1: Something[String] = Something(something)
    Kotlin, on the other hand, won’t compile something like this:
    data class Something<T>(val value: T)
    Something(1).copy("something")
    I’m wondering if it was an explicit design decisions, or maybe something that just hasn’t been implemented yet?
    s
    • 2
    • 3
  • d

    David Cuesta

    02/27/2019, 8:25 AM
    Hi guys, question about coroutines. Anyone knows why testList works and testMap launches an error when calling the suspend function?
    import kotlinx.coroutines.delay
    
    suspend fun first(a: Int): Int {
        delay(100)
        return a + 1
    }
    
    suspend fun testMap(a: Map<String, Int>): Int {
    
        a.forEach { key, value ->
            first(value)
            println(value)
        }
    
        return 0
    }
    
    suspend fun testList(a: List<Int>): Int {
    
        a.forEach {
            first(it)
            println(it)
        }
    
        return 0
    }
    g
    • 2
    • 7
  • e

    Edgars

    02/27/2019, 11:04 AM
    Pardon if there's a better-suited channel for this, but I've finally thought of a decent project that I could do. I want to make it multi-platform (OS-wise). 1) What would be better for this task - Kotlin/JVM or Kotlin/Native? 2) How do I go about doing the GUI so that it works on all platforms? Swing (if JVM)? I'm not really experienced with making desktop applications. I have a couple of years of professional experience with Kotlin/JVM, so it'd be easier for me to do it that way + whatever GUI framework, but perhaps there's an advantage doing it the native way?
    c
    r
    • 3
    • 2
  • l

    louiscad

    02/27/2019, 1:58 PM
    Has anyone encountered that error regarding
    jvmTarget
    ?
    > Task :some-android-lib-module:compileDebugKotlin FAILED
    e: Unknown JVM target version: 1.7
    Supported versions: 1.6, 1.8
    m
    • 2
    • 8
  • d

    David R.

    02/27/2019, 2:31 PM
    Is there a way in Kotlin to create an empty EnumSet from a reflected enum Class? It seems like I can do it with Java, but not with Kotlin based on the enum type constraints and inference (and if I take Java code and paste it into Kotlin and have IntelliJ do the auto convert, it fails)
    m
    • 2
    • 10
  • l

    Lamberto Basti

    02/27/2019, 3:00 PM
    Someone knows how to locally add a multiplatform project as a dependecy for a JVM project? I've posted my usecase here: https://discuss.kotlinlang.org/t/how-do-you-import-a-module-of-a-local-multiplatform-library-using-gradle/11752
    d
    • 2
    • 3
  • l

    LeoColman

    02/27/2019, 4:04 PM
    Guys, in a week from now I'll be organizing a Kotlin Dojo. The idea is bringing the Java-people to start playing around with Kotlin, and maybe use it in their projects. Do you have any tips for this? Maybe a dojo-like problem?
    m
    k
    +2
    • 5
    • 4
  • h

    hudsonb

    02/27/2019, 11:51 PM
    I have a a Polygon class. I'm adding several operators and useful functions. Would you add these as methods in the class, or as extension functions? Not concerned with Java interop.
    k
    s
    +2
    • 5
    • 10
  • n

    Nikolai

    02/28/2019, 4:53 AM
    Hi, everyone Sorry if I am writing to wrong channel. I used Kotlin for previous multiplatform project. I am using IDEA, so I used: Kotlin (Mobile Android/iOS) project type. Now I want to develop another project for both mobile platforms but in addition - develop a server on Kotlin as well and want to share same model classes or common code betwee those parts. What is the best project type/setup/structure (preferably in IDEA) for this kind of projects?
    p
    s
    • 3
    • 3
  • d

    Daniel Eke

    02/28/2019, 8:27 AM
    Hi! Is there a Slack group or a discussion somewhere about
    SQLDelight
    ? I have a bunch of questions but I don’t want to bombard them with issues. 😄
    g
    • 2
    • 2
  • j

    JoakimForslund

    02/28/2019, 8:35 AM
    Is there a deep diff util already existing for checking differences in objects within a collection usable in a kotlin multiplatform scenario?
    t
    s
    s
    • 4
    • 8
  • j

    Julien Genoud

    02/28/2019, 11:51 AM
    Hi who can explain me or give me an useful tutorial/usages on
    inline
    i still don't understand it ... thanks
    g
    • 2
    • 2
  • s

    s1m0nw1

    02/28/2019, 1:52 PM
    When I see two instances of the same
    object
    in my application, what might be the issue? Seems to be possible
    g
    n
    +3
    • 6
    • 16
  • a

    Andrew Gazelka

    02/28/2019, 3:30 PM
    I am solving problems on https://projecteuler.net and want to employ TDD. There are often utility methods closely coupled to each problem I am solving, so much so that it might not be appropriate to make a utility class to include top-level functions. How do you recommend me best unit testing these top-level functions? ... is it a bad practice to include the specific top-level functions in the same class as my problem?
    d
    w
    k
    • 4
    • 20
  • a

    Andrew Gazelka

    02/28/2019, 4:34 PM
    have https://gist.github.com/andrewgazelka/63b8665928ae68dd00bdaed40161e9c2 and getting when testing (
    1.3.21
    )
    i
    • 2
    • 5
  • c

    CLOVIS

    02/28/2019, 5:31 PM
    Is there a server for multiplatform Kotlin? I have a few questions but don't know where to ask
    h
    r
    • 3
    • 4
  • a

    Andrew Gazelka

    03/01/2019, 12:21 AM
    iyo is using HOF with builder pattern sometimes bad because people can execute arbitrary code in them?
    k
    • 2
    • 5
  • t

    tipsy

    03/01/2019, 6:56 AM
    i'm seeing
    java.lang.IllegalStateException: Resource not found in classpath: kotlin/coroutines/coroutines.kotlin_builtins
    intermittently in a tests that use to work fine. it only seems to happen on windows (build seems to work on linux consistently, and it's never failed on travis). has anyone run into this?
    • 1
    • 1
  • m

    mbonnin

    03/01/2019, 10:36 AM
    Hi! Are there any recommendations on how to use exceptions in kotlin ? With the lack of checked exceptions, we've been hit a couple of times by missing
    catch
    clauses. For an example IOExceptions on files/connections that made the app crash while we should have just shown an error screen. We were considering removing exceptions altogether from our codebase and just rely on return values. Legacy java dependencies like
    File
    would still need
    catch
    blocks and that's okay. But then we realized that even new libs like retrofit-coroutines throw exceptions. How are you handling this ? Do you have a lot of exception handling in your codebases or do you use return values ? Is it okay for kotlin libs to throw non-fatal exceptions ?
    t
    s
    • 3
    • 53
  • m

    mmaillot

    03/01/2019, 12:50 PM
    Hi! Is it possible to create an extension on enum to get a random value. I have severals enum and for my test, I want to get a random value of this enum. Is it possible?
    d
    m
    d
    • 4
    • 6
Powered by Linen
Title
m

mmaillot

03/01/2019, 12:50 PM
Hi! Is it possible to create an extension on enum to get a random value. I have severals enum and for my test, I want to get a random value of this enum. Is it possible?
d

diesieben07

03/01/2019, 12:53 PM
inline fun <reified E : Enum<E>> randomValue(): E {
    return randomValue(E::class.java)
}

fun <E : Enum<E>> randomValue(cls: Class<E>): E {
    return cls.enumConstants.random()
}
Usage:
val rnd = randomValue<Foo>()
// or
val rnd = randonValue(Foo::class.java)
m

mmaillot

03/01/2019, 12:56 PM
Exactly what I want! thanks!
m

Mark McCormick

03/01/2019, 1:14 PM
YourEnumClass.values().withIndex().shuffled().first().value
d

diesieben07

03/01/2019, 1:15 PM
That is way slower.
d

Dico

03/02/2019, 1:23 PM
enumValues<E>().let { it[Random.nextInt(size)] }
View count: 4