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

    kenkyee

    09/08/2018, 2:24 AM
    when writing a Kotlin DSL, is there a better way of having a lambda accept a list of enums than using the "plus" overloading technique like this? With the unary plus technique, you end up w/ DSL code that looks like: authMethod { +PIN +CHIP } but it'd be nice to remove the '+' prefix
    -.php
    s
    l
    • 3
    • 8
  • k

    karelpeeters

    09/08/2018, 9:01 AM
    Okay what if a library has a data class that's eligible to be inlined, and then a new version comes out that does something that breaks that, for example it adds a constructor with some logic. Normally code that was compiled would work with the new constructor, but with inline classes it would be ignored.
    c
    • 2
    • 5
  • d

    Daniel Tam

    09/08/2018, 12:35 PM
    just out of curiosity, when is Kotlin 1.3 expected to release? If it's in the next few months then Vertx 3.6 can release with Kotlin 1.3 😄 edit: heh I suppose it's not just purely out of curiosity then
    n
    • 2
    • 1
  • j

    Jakub

    09/08/2018, 2:35 PM
    How to do that in nice declarative style? Somehow with
    map
    operator?
    r
    t
    • 3
    • 4
  • j

    Jakub

    09/08/2018, 3:12 PM
    sorry, I meant, I wanna map
    List<UserApi>
    to
    List<User>
    r
    • 2
    • 2
  • m

    Marcin Wisniowski

    09/08/2018, 6:10 PM
    override fun onBackPressed() {
            drawer?.run {
                if (!isDrawerOpen) {
                    openDrawer()
                    this
                } else null
            } ?: super.onBackPressed()
        }
    n
    c
    k
    • 4
    • 7
  • p

    Paul Woitaschek

    09/09/2018, 9:49 AM
    Does it make sense to let the class implement an interface instead of using an anonymous inner class - in regards to object allocation?
    e
    • 2
    • 7
  • j

    jw

    09/09/2018, 11:48 PM
    Compile-testing
    a
    t
    • 3
    • 6
  • a

    Ayden

    09/10/2018, 2:42 AM
    Hi guys. I can create an iOS app by using Kotlin right now? https://kotlinlang.org/docs/reference/native-overview.html#target-platforms
    g
    • 2
    • 2
  • j

    Janar

    09/10/2018, 11:17 AM
    Hi Guys, I have a code like this:
    import java.security.MessageDigest
    fun foo(rp: String) {
        return bar(rp)
    }
    private fun bar(rp: String): ByteArray {
        return MessageDigest.getInstance("SHA-256").digest(rp.toByteArray())
    }
    The generarted code for kotlin uses:
    Intrinsics.checkParameterIsNotNull
    for
    foo
    and generates
    if (rpId ==null)
    in
    bar
    . In the later case it throws a
    TypeCastException
    in case of null and in former an
    IllegalArgumentException
    . So why does generated code need to handle null checks differently??
    r
    d
    d
    • 4
    • 14
  • b

    bdawg.io

    09/10/2018, 4:25 PM
    I was trying to do
    Command+LMB
    on it, but I’ll give
    Ctrl+B
    a try next time
    s
    k
    • 3
    • 3
  • c

    christophsturm

    09/10/2018, 5:17 PM
    is there a way to find the name of the source file for a class?
    • 1
    • 1
  • k

    karelpeeters

    09/10/2018, 5:20 PM
    Why do you need this?
    c
    d
    +3
    • 6
    • 11
  • v

    ValV

    09/10/2018, 9:02 PM
    Isn't the question about
    check
    in #getting-started channel of any interest for you?
    v
    • 2
    • 6
  • k

    kristofdho

    09/10/2018, 11:10 PM
    you could do
    fun <T> Sequence<T>.takeWhileInclusive(pred: (T) -> Boolean): Sequence<T> = take(count(pred) + 1)
    i
    c
    • 3
    • 3
  • d

    DALDEI

    09/10/2018, 11:21 PM
    Is it considered a reportable bug if Java native reflection APIs crash (NPE) when reflecting kotlin classes?
    i
    • 2
    • 1
  • d

    Dias

    09/10/2018, 11:44 PM
    Hi all, I have a few questions about kotlin. Why does kotlin not complain about unsafe casting from nullable? like
    var a: String? = null
    
        var b: String = a as String
    it doesn’t warn that this kind of cast might not be safe
    d
    s
    • 3
    • 8
  • d

    Dias

    09/10/2018, 11:56 PM
    Another question about coroutines: in the tutorial there is an example where there process waits for coroutine to finish computation before it gets cancelled
    fun main(args: Array<String>) = runBlocking<Unit> {
        val startTime = System.currentTimeMillis()
        val job = launch {
            var nextPrintTime = startTime
            var i = 0
            while (i < 5) { // computation loop, just wastes CPU
                // print a message twice a second
                if (System.currentTimeMillis() >= nextPrintTime) {
                    println("I'm sleeping ${i++} ...")
                    nextPrintTime += 500L
                }
            }
        }
        delay(1300L) // delay a bit
        println("main: I'm tired of waiting!")
        job.cancelAndJoin() // cancels the job and waits for its completion
        println("main: Now I can quit.")
    }
    but the code below that
    fun main(args: Array<String>) = runBlocking<Unit> {
        val job = launch {
            try {
                repeat(1000) { i ->
                    println("I'm sleeping $i ...")
                    delay(500L)
                }
            } finally {
                println("I'm running finally")
            }
        }
        delay(1300L) // delay a bit
        println("main: I'm tired of waiting!")
        job.cancelAndJoin() // cancels the job and waits for its completion
        println("main: Now I can quit.")
    }
    is not being awaited to finish it’s job before cancellation
    m
    • 2
    • 2
  • w

    wei

    09/11/2018, 1:49 AM
    I’ve got a question about comparing two enum values of the same schema but of different package path. They were both generated with avro. In my code, I can compare them like so:
    val a = com.mycompany.path1.MyEnum.GOOD
    val b = com.mycompany.path2.MyEnum.GOOD
    if (a == b) {
        println("a == b")
    }
    This code actually compiles and runs. However, when I created 2 different enum classes by hand and put them into 2 paths, the code won’t compile and it will say something like:
    Operator '==' cannot be applied to 'com.mycompany.path1.myEnum' and 'com.mycompany.path2.MyEnum'
    Why?
    s
    d
    +2
    • 5
    • 11
  • d

    Doru N.

    09/11/2018, 8:43 AM
    Hey there. I got a situation where I must filter out some items from a read only list which represents property of an object. A more visual representation of the nested classes would be like this:
    data class DataSourceResponse(val response: Response)
    data class Response(val notifications: List<Notification>)
    data class Notification(id: Int)
    I have a function which takes a DataSourceResponse as a param and a callback, which should return a modified DataSourceResponse, filtering out some of the notifications from it. How should I implement this filtering and copy, considering the given model classes above. (immutable notifications list). The closest I got, was doing something like this:
    callback.onDataLoaded(
        paramDataSourceResponse.copy (
            response = paramDataSourceResponse.response.copy (
                notifications = paramDataSourceResponse.response.notifications.filter { check(it) }
            )
        )
    )
    but it looks kinda ugly to me. Also, not having every class made data class, would make it even uglier. Are there any other solutions for this?
    h
    p
    • 3
    • 11
  • d

    david-wg2

    09/11/2018, 8:52 AM
    private fun whenTest(a: Boolean, b: Boolean) = when {
        a && b -> ""
        !a && b -> ""
        a && !b -> ""
        !a && !b -> ""
    }
    e
    p
    • 3
    • 10
  • c

    colljos

    09/11/2018, 9:24 AM
    Gradle / Kotlin question (not sure where to ask) https://kotlinlang.org/docs/reference/visibility-modifiers.html#modules How does one use the
    internal
    keyword within the same module but from a different source set than
    main
    ,
    test
    ? (eg. I’m trying to use internal from an
    integrationTest
    source set in the same module)
    h
    • 2
    • 1
  • g

    ghedeon

    09/11/2018, 10:35 AM
    yeah, got confused by that selector in the top-right corner with "JVM" label. So... either regexp or third-party libraries?
    g
    k
    h
    • 4
    • 3
  • a

    Aregev2

    09/11/2018, 10:58 AM
    I was noticing a wierd issue in the toString method of `inline classes`: Given this piece of code:
    fun main(args: Array<String>) {
        val wi = WrapInt(1)
        val ws = WrapString("1")
        println(wi)
        println(ws)
    }
    
    inline class WrapInt(private val x: Int)
    inline class WrapString(private val x: String)
    In 1.3-M2 the the toString method was changed to a structure of a
    data class
    but when calling it on a class that wraps a string it just prints out the contained string... (In JVM)
    WrapInt(x=1)
    1
    In Kotlin Native though it works as expected... giving this output:
    WrapInt(x=1)
    WrapString(x=1)
    • 1
    • 2
  • a

    Ahmed Mamdouh

    09/11/2018, 1:20 PM
    I have a question about visibility of fields in data classes , i want it to be private but not sure how to set and get the value , putting var before field parameters can ensure that it has getters and setters but what if i put private before the fields in the parameter? Should i write a getters and setters myself ?
    h
    s
    • 3
    • 6
  • r

    robstoll

    09/11/2018, 2:23 PM
    Is there a reason java.nio.file.Path isn't mentioned on https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.io/index.html but only the kind of old scool java.io.File? I was surprised to see that there aren't any extension methods on Path such as
    exists
    .
    h
    • 2
    • 2
  • p

    Paul Woitaschek

    09/11/2018, 5:30 PM
    -.kt
    l
    s
    +2
    • 5
    • 14
  • s

    Slackbot

    09/11/2018, 7:03 PM
    This message was deleted.
    :stackoverflow: 1
    k
    • 2
    • 1
  • d

    Daniele Segato

    09/11/2018, 7:13 PM
    I've several enum that I use to map with JSON values from GSon and I've this piece of code that I've already copied 4 times at least and slightly edited... Is there a way to extract the part of the
    companion object
    into some kind of reusable code? The main problem is I need the
    Enum.values()
    statically and the class name for strings. I also need to access the
    jsonValue
    in the enum, but I can put it in an interface of the enum I guess, so that's not a big deal... Any suggestion? See the code below (please answer in thread)
    Enum__static__companion_automatic_generation_.kt
    k
    a
    a
    • 4
    • 31
  • t

    tschuchort

    09/11/2018, 7:14 PM
    is there any way to create an empty array of a generic type?
    a
    s
    +4
    • 7
    • 21
Powered by Linen
Title
t

tschuchort

09/11/2018, 7:14 PM
is there any way to create an empty array of a generic type?
a

Andreas Sinz

09/11/2018, 7:15 PM
Generic type unknown at compile-time?
s

Shawn

09/11/2018, 7:16 PM
you may have to reify your generic type and inline the function in question
inline fun <reified T> emptyGenericArray(): Array<T> {
  return arrayOf()
}
b

bloder

09/11/2018, 7:17 PM
maybe this?
inline fun <reified T> genericArrayOf() : Array<T> = arrayOf()
oh sorry LOL
👍 1
t

tschuchort

09/11/2018, 7:20 PM
not possible. The method is a class method so it can not be reified. Basically I have to implement an interface of the sort
fun <A : Something> foo(bar: Class<A>): Array<A>
a

Allan Wang

09/11/2018, 7:48 PM
If the empty array is an immutable placeholder, you can look at the empty array implementation in kotlin: https://github.com/JetBrains/kotlin/blob/1.2.60/core/builtins/src/kotlin/ArrayIntrinsics.kt#L24 You can sort of cast an empty array for any type
k

kristofdho

09/11/2018, 7:50 PM
that's what i said & deleted, since the exact same problem occurs at the
arrayOfNulls<T>(0)
call,
T
is again not reified
t

tschuchort

09/11/2018, 7:53 PM
It's probably not supposed to be immutable. "The caller of this method is free to modify the returned array; it will have no effect on the arrays returned to other callers." Tbh I have no idea how anyone is supposed to implement this
god I hate the JVM
k

kristofdho

09/11/2018, 7:54 PM
if it's empty, there is nothing to modify, it'll always be immutable
t

tschuchort

09/11/2018, 7:57 PM
there's
fun <T> Array<T>.plus(element: T): Array<T>
though and if I return an
arrayOfNulls<Any?>(0) as Array<T>
than calling that method on it will fail
k

kristofdho

09/11/2018, 8:00 PM
the
plus
function already contains the type in
this
(being an
Array<T>
), if you're confused as to why it's not reified
t

tschuchort

09/11/2018, 8:09 PM
I'm just saying there is no way I can create an empty
Array<T>
for any T
even
arrayOfNulls<Any?>(0) as Array<SomeClass?>
already doesn't work 😕
k

kristofdho

09/11/2018, 8:22 PM
i'm trying but i cant even find something hacky. deeper issue is the bad method signature, because like you say, you can't just magically pull a typed array out of your ass
b

bloder

09/11/2018, 8:30 PM
Well, it would be good if you could use list instead of array
fun <T : Any> genericListOf() : List<T> = arrayOf<KClass<T>>().mapNotNull { it.objectInstance }
Do you know any solution like that to arrays?
k

kristofdho

09/11/2018, 8:58 PM
i do not recomend using it, but i found this
override fun <T : Something> foo(bar: Class<T>): Array<T>
    = java.lang.reflect.Array.newInstance(bar, 0) as Array<T>
d

diesieben07

09/11/2018, 9:06 PM
java.lang.reflect.Array.newInstance
is the way to go if you need this. It's ugly but perfectly fine to use.
t

tschuchort

09/12/2018, 9:07 PM
Thx that looks like it might work. The method probably isn't gonna be called often so reflection shouldn't be a problem
d

diesieben07

09/13/2018, 7:16 AM
It's a JVM intrinsic, it's not much slower than just creating a new array the "normal way".
View count: 4