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
announcements
  • h

    Hullaballoonatic

    11/10/2019, 6:33 PM
    so when you have an array as a property of a data class, idea recommends you override equals and hashcode, then provides you with an implementation. Is that the same as the default data class implementation? if no, why not? if yes, why would the warning disappear?
    k
    • 2
    • 1
  • j

    jojo.lichtenberger

    11/11/2019, 9:09 AM
    Hey, I'd love to use Kotlin in a multi-module Open Source maven project. I've used it in one module exclusively. In other modules I'm currently using Java 13. Would you advise on using Kotlin and Java in a single module? I'd love to switch but don't want to rewrite everything. I haven't tried yet, but I guess the IntelliJ Java to Kotlin Converter for classes doesn't produce idiomatic Kotlin code, so I think it's better to just call the Java code from Kotlin and vice versa. Would you advise on mixing Java and Kotlin in a single module? Are there any pitfalls? Or should I have Java and Kotlin modules seperated from each other?
    j
    g
    h
    • 4
    • 20
  • s

    Slackbot

    11/11/2019, 10:08 AM
    This message was deleted.
    f
    j
    • 3
    • 3
  • b

    Burkhard

    11/11/2019, 1:22 PM
    How do I enable experimental type inference again. I’m sure I read somewhere that it is possible, but I can’t seem to find any article about it
    k
    • 2
    • 2
  • g

    ghedeon

    11/11/2019, 3:47 PM
    Is it possible to use
    Result<T>
    in Java? All extensions seem to be
    InlineOnly
    , how would you fold this class?
    d
    • 2
    • 2
  • i

    ianrumac

    11/11/2019, 4:13 PM
    I wanted Unions so I hacked them in via annotations, if anyone needs them: https://github.com/lotuslambda/unikons
    👍 2
    p
    h
    • 3
    • 8
  • e

    Ellen Spertus

    11/11/2019, 6:35 PM
    Normally I prefer
    when
    to
    switch
    , but I created this monstrosity in order to combine multiple
    is
    cases. Is there a better way without changing the sealed class
    ConnectionState
    (which I might end up doing)?
    if (savedConnectionState is ConnectionState.Isolated) {
        view.initializeButtons(true, false)
    } else if (savedConnectionState is ConnectionState.Advertising || 
        savedConnectionState is ConnectionState.Discovering ||
        savedConnectionState is ConnectionState.Initiating ||
        savedConnectionState is ConnectionState.Authenticating ||
        savedConnectionState is ConnectionState.Connecting) {
        view.initializeButtons(false, false)
    } else if (savedConnectionState is ConnectionState.ReadyToSend) {
        view.initializeButtons(false, true)
    } else if (savedConnectionState is ConnectionState.Failure) {
        view.initializeButtons(false, false)
    }
    p
    r
    • 3
    • 5
  • n

    nwh

    11/12/2019, 12:17 AM
    Are there plans for expanding the current commenting system of Kotlin? For example, being able to reference a specific function by argument type like
    See also: [String.toUpperCase(Locale)]
    So that overloaded functions can be differentiated?
    a
    • 2
    • 1
  • a

    Animesh Sahu

    11/12/2019, 5:53 AM
    apply with a suspendable block?
    g
    • 2
    • 1
  • k

    Kate

    11/12/2019, 8:15 AM
    @Alina Dolgikh [JB] how can I join your Russian kotlin slack workspace?
    a
    • 2
    • 2
  • m

    Mani

    11/12/2019, 9:20 AM
    casting l1 as ArrayList is working fine
    d
    d
    +2
    • 5
    • 25
  • p

    Paul Woitaschek

    11/12/2019, 10:28 AM
    How can I convert this code to kotlin?
    public static JsonAdapter<?> create(Class<?> rawType) {
        return new SafeEnumJsonAdapter<>((Class<? extends Enum>) rawType).nullSafe();
      }
    d
    d
    • 3
    • 8
  • s

    Stephan Schroeder

    11/12/2019, 3:27 PM
    So i want to deserialize a string into a
    Data.Single
    but it fails.
    sealed class Data<T: Any> {
        class Single<T: Any>(val single: T?): Data<T>()
        class ListOf<T: Any>(val list: List<T>): Data<T>()
    }
    Could the reason for the mismatch be that the constructor parameter
    single
    is nullable?? The error message is: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of
    uk.co.whichdigital.pricingengine.Data$Single
    (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (‘up and running’)
    Here is my current jsonMapper config:
    private val jsonMapper = ObjectMapper().apply {
            registerModule(KotlinModule())
            configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)
            configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        }
    UPDATE: I changed the code to `Data.Single`’s generic parameter is nullable
    class Single<T>(val single: T): Data<T>()
    but the error message didn’t change.
    d
    • 2
    • 16
  • o

    Oleg Siboglov

    11/12/2019, 5:02 PM
    Could someone please tell me what the Kotlin equivalent of this
    <T extends LifecycleOwner & ViewModelStoreOwner>
    would be?
    w
    • 2
    • 2
  • s

    Sandeep Gurram

    11/13/2019, 7:25 AM
    Hi Guys, are scoped function(run, let, apply, also) having anything to do with threads ? are there thread safe ?
    s
    t
    • 3
    • 3
  • a

    Andreas Unterweger

    11/13/2019, 10:33 AM
    hello all, i have a question regarding mockk kotlin mocking framework. how can i mock all instances of an class? i tried:
    val ibMock = mockkClass(InstalledBase::class)
    every { ibMock.getModelDescriptions() } returns emptyList<ModelDescription>()
    but it doesnt work. getModelDescriptions() still returns another list. i have no access to the object instaledbase in my test, but i want that getModelDescriptions() always returns an empty list
    s
    m
    • 3
    • 12
  • b

    Brian Carbone

    11/13/2019, 3:55 PM
    get() = field.coerceAtLeast(0)
    I don't know how to make a delegate to replace this
    l
    c
    • 3
    • 9
  • l

    louiscad

    11/13/2019, 4:32 PM
    Hi, I'm looking for your recommendations to parse a simple xml file that doesn't go deeper than 3 levels. Here's an example of the kind of files I'm going to parse: https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-runtime/maven-metadata.xml In the end, I want to get a list of the available versions. Is there a light library that I should use, or is that overkill and I should just use Kotlin stdlib to do it? Thanks for your input!
    e
    m
    • 3
    • 4
  • f

    Fudge

    11/13/2019, 8:14 PM
    Were smart casts recently changed to work on mutable variables??!
    r
    z
    • 3
    • 4
  • k

    Ky Leggiero

    11/13/2019, 10:54 PM
    I wish I could hate this 😂
    👌 1
    🤣 6
    😂 28
    😅 6
    j
    • 2
    • 1
  • t

    Tauhid Rehman

    11/14/2019, 2:26 AM
    does anyone know if kotlin has a built in library that uses the
    .mask
    function? basically I need to mask a certain number of integers with a
    *
    t
    • 2
    • 2
  • u

    ursus

    11/14/2019, 5:06 AM
    Hi, I want to ask about local functions. Is there any penalty to calling a function which defines a local function inside it? Does it get "redefined" every call or is there something clever in the compiler?
    t
    • 2
    • 1
  • m

    Mohamed Ibrahim

    11/14/2019, 7:03 AM
    how to use kotlin sealed classes in java/Rxjava
    t
    p
    • 3
    • 4
  • c

    Cyberpunk Keanu

    11/14/2019, 4:21 PM
    Hey all, I'm new here. With my recent discovery of Ktor as an Android Developer working in Kotlin, I'm more intrigued about building my own Kotlin Written Server Backends without having to rely much on my team's backend developers. However, almost no one here writes server backend in Kotlin. Everyone's on Node.js & Express.js, saying Ktor doesn't have a Future Scope. So asking you guys, can Ktor grow into something which can be use to write Production level Server Backends?
    f
    d
    +5
    • 8
    • 18
  • b

    Ben Madore

    11/14/2019, 9:09 PM
    anyone else using spotless gradle plugin with ktlint? and finding that it doesn’t seem to actually check the same things at ktlint? i.e. if i run
    gradle spotlessCheck
    i get no issues, but i get a lot when i run
    ktlint
    s
    • 2
    • 3
  • e

    eekboom

    11/14/2019, 10:13 PM
    I assume that
    tasks.compileKotlin {
    	kotlinOptions.jvmTarget = "1.8"
    }
    is the same as
    tasks.compileKotlin.configure {
    	kotlinOptions.jvmTarget = "1.8"
    }
    Can somebody explain to me how this magic works?
    compileKotlin
    is a property of type
    TaskProvider<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>
    which is an interface with two abstract methods, so it can't be SAM, right?
    s
    • 2
    • 1
  • e

    eekboom

    11/14/2019, 10:18 PM
    Ok, it seems that rubber ducking works even when just talking into the void 😉 I found this in `NamedDomainObjectProviderExtensions`:
    operator fun <T> NamedDomainObjectProvider<T>.invoke(action: T.() -> Unit) =
        configure(action)
    Nice.
    p
    • 2
    • 1
  • a

    Akhil Sunny

    11/14/2019, 11:00 PM
    Hey All , I am trying to write tests for a Kotlin MPP - for iOS testing found using a simulator - https://github.com/JetBrains/kotlin-native/issues/2426 -
    task iosTest {
        def device = project.findProperty("iosDevice")?.toString() ?: "iPhone 8"
        dependsOn 'linkTestDebugExecutableIos'
        group = JavaBasePlugin.VERIFICATION_GROUP
        description = "Runs tests for target 'ios' on an iOS simulator"
    
        doLast {
            def binary = kotlin.targets.ios.compilations.test.getBinary('EXECUTABLE', 'DEBUG')
            def infoPlistSrc = file("$rootProject.projectDir/src/iosTest/resources/Info.plist")
            def infoPlistDest = file("$binary.parentFile/Info.plist")
    
            Files.copy(infoPlistSrc.toPath(), infoPlistDest.toPath(), StandardCopyOption.REPLACE_EXISTING)
    
            exec {
                commandLine 'export', 'SIMCTL_CHILD_CFNETWORK_DIAGNOSTICS=3'
                commandLine 'xcrun', 'simctl', 'spawn', device, binary.absolutePath
            }
        }
    }
    - this simulator runs in a terminal and executes the tests. But I can't find any reports generated by it(html/xml ). Is it possible to have reports generated by this simulator ? or is there any other way to generate reports while unit testing a Kotlin iOS output ? . Pls help
    b
    • 2
    • 9
  • b

    bodiam

    11/14/2019, 11:23 PM
    Is there any ETA on Kotlin 1.3.60 ?
    r
    b
    +3
    • 6
    • 15
  • j

    james

    11/14/2019, 11:45 PM
    I'm wondering if someone can show me the Kotlin-idiomatic way to solve the following. I have a list of objects which gets returned from a repo and I'd like to transform them into another object, while throwing away objects that are deemed "invalid".. where invalid in this example is if
    it.nullableField
    is null. I've tried the following, but it doesn't work as expected because the smart cast fails, as seen in comment:
    repo.getThings()
        .mapNotNull {
            if (it.nullableField != null) {
                SomeOtherThing(
                    id = it.id,
                    name = it.name,
                    requiredField = it.nullableField // compiler error: Smart cast to String is impossible because it.nullableField is a public API property declared in a different module
                )
            } else null
        }
    s
    b
    m
    • 4
    • 10
Powered by Linen
Title
j

james

11/14/2019, 11:45 PM
I'm wondering if someone can show me the Kotlin-idiomatic way to solve the following. I have a list of objects which gets returned from a repo and I'd like to transform them into another object, while throwing away objects that are deemed "invalid".. where invalid in this example is if
it.nullableField
is null. I've tried the following, but it doesn't work as expected because the smart cast fails, as seen in comment:
repo.getThings()
    .mapNotNull {
        if (it.nullableField != null) {
            SomeOtherThing(
                id = it.id,
                name = it.name,
                requiredField = it.nullableField // compiler error: Smart cast to String is impossible because it.nullableField is a public API property declared in a different module
            )
        } else null
    }
s

streetsofboston

11/14/2019, 11:48 PM
Insert a
.filter { it.nullableField != null }
into the chain. Then just do
.map { SomeOtherThing( ..., ..., requiredField = it.nullableField!!) }
You still would need the
!!
check; smart-casting won’t work in this case
j

james

11/14/2019, 11:49 PM
I considered that, and I considered just adding !! to
it.nullableField
where my comment is. both of these seem to work, but I'm wondering what the idiomatic way is?
using
filter
feels more readable at least
b

basher

11/14/2019, 11:51 PM
repo.getThings()
    .mapNotNull { thing ->
        thing.nullableField?.let {
            SomeOtherThing(
                id = thing.id,
                name = thing.name,
                requiredField = it
            )
        }
    }
j

james

11/14/2019, 11:58 PM
I considered that too, Ben, but my main concern there is that it limits me to a single field being checked.
I'm leaning towards using
filter
anyone have any other ways of achieving it?
b

basher

11/14/2019, 11:58 PM
oh i see 👍
m

Matteo Mirk

11/19/2019, 12:29 PM
I think
filter
is the best option
View count: 1