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

    Viral Thakker

    09/04/2018, 7:14 AM
    can anyone explain what exactly contract is ?
    g
    • 2
    • 2
  • v

    Viral Thakker

    09/04/2018, 7:15 AM
    Any link/blog will be appreciated
    a
    • 2
    • 1
  • d

    Daniele Segato

    09/04/2018, 8:38 AM
    I'm trying to migrate some code from Java to Kotlin, it has an annotation where I used constants inside the annotation (in Java):
    @IntDef(
                flag = false,
                value = {
                        AspectRatioMode.AUTO,
                        AspectRatioMode.BY_WIDTH,
                        AspectRatioMode.BY_HEIGHT,
                }
        )
        public @interface AspectRatioMode {
            int AUTO = 0;
            int BY_WIDTH = 1;
            int BY_HEIGHT = 2;
        }
    @IntDef
    is an Android annotation allowing to define an annotation for Integer constants on Integers:
    @AspectRatioMode
    int myMode = AspectRatioMode.AUTO; // can only be one of AUTO / BY_WIDTH / BY_HEIGHT
    While in kotlin the conversion would be:
    @IntDef(flag = false, value =[
            AspectRatioMode.AUTO,
            AspectRatioMode.BY_WIDTH,
            AspectRatioMode.BY_HEIGHT
        ])
        annotation class AspectRatioMode {
            companion object {
                val AUTO = 0
                val BY_WIDTH = 1
                val BY_HEIGHT = 2
            }
        }
    but I get an error on `companion object`: "Members are not allowed in annotation class" I can move those constants out:
    object AspectRatioModeConst {
            const val AUTO = 0
            const val BY_WIDTH = 1
            const val BY_HEIGHT = 2
        }
    
        @IntDef(flag = false, value = [
            AspectRatioModeConst.AUTO,
            AspectRatioModeConst.BY_WIDTH,
            AspectRatioModeConst.BY_HEIGHT
        ])
        annotation class AspectRatioMode
    but that is a lot uglier then Java where I could more cleanly use the annotation directly for constants.
    @AspectRatioMode
    val myGoodMode : Int = AspectRatioMode.AUTO; // I want this
    val myBadMode : Int = AspectRatioModeConst.AUTO; // not this
    Is there any other way I can obtain the same result of Java with Kotlin?
    c
    g
    • 3
    • 10
  • d

    Daniele Segato

    09/04/2018, 9:11 AM
    Is there a way to access the raw field value of a
    var
    bypassing a getter? See the code
    Anyway_to_bypass_the_getter_.kt
    p
    • 2
    • 2
  • d

    Daniele Segato

    09/04/2018, 9:37 AM
    In my migration from Java to Kotlin I've a bunch of interfaces that re-define methods of the Framework for various reasons... The class
    View
    is part of the Android framework and has methods like:
    public int getPaddingLeft() { ... }
    my Java interface was:
    interface MyInterface {
        int getPaddingLeft();
    }
    And for my widget in java I just had to implement the interface without doing anything else, the methods were already there. With Kotlin tough, the interface become a
    val
    declaration and the compiler complains I should implement those `val`s. If I do I get the error:
    Accidental override: The following declarations have the same JVM signature (getPaddingRight()I): 
    *  public open fun <get-paddingRight>(): Int defined in my.package.MyWidget
    *  public open fun getPaddingRight(): Int defined in my.package.MyWidget"
    the error happens on the
    get()
    The second one is of course the Platform method. Is there a way to tell Kotlin those are the same thing and I do not need to override anything? see kotlin code
    Interfaces_overlapping_Java_classes_getters.kt
    g
    k
    • 3
    • 15
  • b

    Bernhard

    09/04/2018, 10:42 AM
    is there a way to parse JSON in a simple way without pulling in gson/jackson or other libs?
    n
    d
    +3
    • 6
    • 12
  • j

    juliocbcotta

    09/04/2018, 4:43 PM
    Is there any work/GitHub to have Rx Schedulers backed by coroutines? Tried to Google it, but a lot of Rx vs Coroutines got in the way.
    e
    j
    • 3
    • 3
  • u

    Uldis Indriksons

    09/05/2018, 8:33 AM
    Question about null-safe call on nullable property. In our team we were discussing null-safety topic and wondering how kotlin
    .?
    works. So we decompiled it using AndroidStudio. The outcome was unexpected for us. The class:
    class NullSafeCall {
    
        var nullableString: String? = null
    
        fun nullSafe() {
            nullableString?.length
        }
    }
    Decompiled
    nullSafe
    method:
    public final void nullSafe() {
          String var10000 = this.nullableString;
          if (this.nullableString != null) {
             var10000.length();
          }
       }
    It looks to me it can still get NPE as a result of nasty race-condition. Can someone explain to me wether it’ s kotlin issue or decompiler output is not quite accurate.
    s
    • 2
    • 2
  • d

    david-wg2

    09/05/2018, 9:26 AM
    is there anything built in to simplify snippets like this?
    val myValue = try { 
    	getValue() 
    } catch (e: Exception) { 
    	throw MyException()
    }
    s
    g
    • 3
    • 13
  • d

    Daniele Segato

    09/05/2018, 10:36 AM
    @karelpeeters what do you mean by delegate to it? can you make an example?
    a
    d
    k
    • 4
    • 17
  • w

    wakingrufus

    09/05/2018, 1:17 PM
    Is there a good analysis somewhere of json serialization options? jackson vs kotlinx (#serialization ) vs #klaxon ? I have been using jackson, but I am wondering if I should spend some time to switch to something else, if it is more lightweight, or involves less dependencies
    g
    • 2
    • 8
  • u

    Uzi Landsmann

    09/05/2018, 1:41 PM
    We’ve done a simple test with serializations. We send a list to a rest endpoint which iterated through it. We compared serializing to
    java.util.List
    with
    kotlin.collections.List
    and were surprised to find that the Kotlin serialization took twice the time. The theory is that Jackson serializes to a Java list, and then Kotlin converts it to a Kotlin list. If that is true, then it would be worth the time experimenting with native Kotlin serializers.
    🇳🇴 3
    d
    g
    • 3
    • 2
  • d

    Daniele Segato

    09/05/2018, 4:15 PM
    Sometimes with Android Studio (but I guess it's the same with Intellij, that's why I ask here and not in #android ) I place a breakpoint on a kotlin piece of code and the Debugger DO NOT stop on it... If I place the breakpoint earlier and step it DOES pass there.. so the breakpoint isn't working. Anyone else experiencing this?
    n
    t
    • 3
    • 3
  • e

    eygraber

    09/06/2018, 4:28 AM
    Looking for input on if it's worth filing a request on YouTrack for this: The implementation of set difference in the stdlib is:
    public operator fun <T> Set<T>.minus(elements: Iterable<T>): Set<T> {
        val other = elements.convertToSetForSetOperationWith(this)
        if (other.isEmpty())
            return this.toSet()
        if (other is Set)
            return this.filterNotTo(LinkedHashSet<T>()) { it in other }
        val result = LinkedHashSet<T>(this)
        result.removeAll(other)
        return result
    }
    My request is that an initial capacity get added to the
    LinkedHashSet
    that is returned if
    other
    is a
    Set
    . I know there's no way to know what the value would be, but it could certainly be approximated at better than the default by doing
    LinkedHashSet<T>(this.size - other.size)
    . That way, in the "best case" where everything in
    other
    is in the set, the capacity will be correct, and in the "worst case", where nothing in
    other
    is in the set, the capacity will have to grow to the size of the set, but we'll likely be closer to that than the default (16). Am I missing something / is this not necessary, or is this worth filing a bug over?
    k
    g
    • 3
    • 3
  • m

    Manish

    09/06/2018, 9:02 AM
    is there any possibility of getting tickets to upcoming Kotlin conf @ Amsterdam?
    g
    • 2
    • 2
  • p

    Paul Woitaschek

    09/06/2018, 9:55 AM
    Is there an open feature request for named arguments on type aliases?
    d
    • 2
    • 1
  • p

    Paul Woitaschek

    09/06/2018, 9:59 AM
    Untitled.kt
    d
    • 2
    • 6
  • i

    Ivan

    09/06/2018, 11:52 AM
    Hey, is there a channel dedicated to Kotlin/Native discussion?
    s
    • 2
    • 5
  • d

    dave08

    09/06/2018, 4:37 PM
    How could I do something like
    flatMapValues
    to a map? All that currently exists is
    mapValues
    ... My use case is a json hierarchy that needs to be flattened into a
    Map<String, Map<String, JsonElement>>
    . It's something like
    { "level1": { "ns": { "s1": "", "s2": "" } } }
    , and needs to be
    [level1 = [ ns.s1 = "", ns.s2 = ""]]
    . And it's using Gson's JsonObject, etc...
    s
    • 2
    • 3
  • l

    lifter

    09/06/2018, 7:45 PM
    I'm curious if there might be any subtle difference between how
    y
    and
    z
    are defined, or is it really the same thing?
    val x: Int? = 0
    val y = x!!
    val z = x as Int
    s
    d
    • 3
    • 6
  • d

    Dico

    09/06/2018, 8:39 PM
    for the specific use of this lambda, which just prints the hashcode, you can also just declare it as such:
    val printHash: (Any) -> Unit = fun (any: Any) { println(any.hashCode()) }
    g
    • 2
    • 1
  • m

    Michael

    09/06/2018, 8:56 PM
    Just got a new one. One of our guys tried to compile our codebase on Windows, and it threw a
    Exception during code generation
    (The rest of us use linux/mac). Looks like it tried to generate a class file with a name that included the name of a test method - and the method was ``a method name with “quotes” in it``.
    f
    • 2
    • 9
  • l

    lifter

    09/06/2018, 9:29 PM
    Can someone please explain why
    mkDivider1
    compiles but
    mkDivider2
    doesn't? (
    'this' is not defined in this context
    )
    fun mkDivider1(x: Int): (Int.() -> Int) = { this / x }
    fun mkDivider2(x: Int): (Int.() -> Int)? = if (x == 0) null else { this / x }
    By the way, this one does compile:
    fun mkDivider3(x: Int) = if (x == 0) null else fun Int.(): Int { return this / x }
    i
    • 2
    • 16
  • p

    Paul Woitaschek

    09/07/2018, 8:45 AM
    Is this a bug?
    d
    • 2
    • 4
  • n

    Nikky

    09/07/2018, 1:25 PM
    seems like i cannot do this
    var Wrapper<Env>.someProperty by ref(actual::someProperty)
    this only works in the class seems like i do not have access to this or properties of the class i try to extend when using
    by
    btw i am using 1.3-M2 the intent here is to have one large data class , but disallow setting all vars under all circumstances in a DSL only when its matching the Env in the wrapper the extension functions should be there and forward
    e
    • 2
    • 1
  • n

    Nikky

    09/07/2018, 1:50 PM
    i see.. i wonder if i can work around that.. but it seems impossible.. so setter and getter copypasta..
    a
    • 2
    • 5
  • б

    Бежан Александр

    09/07/2018, 5:03 PM
    Where can I ask questions regarding Intellij API ? I need to compile Java file having
    PsiJavaFile
    s
    • 2
    • 4
  • d

    Dominaezzz

    09/07/2018, 7:54 PM
    Is there an elegant way to implement platform-agnostic type-safe bit flags in Kotlin?
    k
    g
    • 3
    • 4
  • r

    rook

    09/07/2018, 9:16 PM
    This seems to still result in a
    List<String?>
    even though I’m filtering for null.
    someListOfNullableStrings.map { it?.let { str -> Foo(str) } }.filter { it != null }
    n
    • 2
    • 3
  • s

    Shawn

    09/07/2018, 10:41 PM
    @Sam there’s the
    @Throws(KClass<out Throwable>...)
    annotation but have you considered not using checked exceptions
    s
    e
    • 3
    • 3
Powered by Linen
Title
s

Shawn

09/07/2018, 10:41 PM
@Sam there’s the
@Throws(KClass<out Throwable>...)
annotation but have you considered not using checked exceptions
s

Sam

09/07/2018, 10:43 PM
Yes, I'm just hoping for compile time constructs that will educate clients about failures than just bailing out with the exception
e

elizarov

09/08/2018, 6:39 AM
Here is a decision chart for you: 1. Are callers of your API supposed to handle failures is some specific way on each call site or are they supposed to handle them globally together with other failures (crash app, write to log, show error dialog, etc)? If only globally - use exceptions, otherwise see below 2. Do callers need additional domain-specific data about failure to handle it (failure position, failure type, etc) or just an indication that an operation has failed? If just an indication of failure - use nullable types, otherwise see below 3. For locally-handled failures with domain-specific additional failure data create a domain-specific sealed class hierarchy to represent successful and failed results with the corresponding data vals. P.S. Sometimes it varies by caller of your API, so extremely widely-used libraries might have several versions of the same function for different uses (see
String.toInt
and
String.toIntOrNull
in the standard library for example).
👏 6
s

Sam

09/08/2018, 1:57 PM
Thanks, a container with results does it
View count: 1