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

    dave08

    05/04/2021, 1:42 PM
    I'm trying to implement a generic spy class to be used in tests for interfaces derived from a base UseCase interface... is there any way to make the spies generic? Or does one have to be made for each derived interface? (See thread for code)
    4 replies · 1 participant
  • a

    Angeles Bilbao

    05/04/2021, 1:44 PM
    Hello everyone, do you know if there is a way to implement a UI skeleton placeholder using Jetpack compose components or should it be done using a third party library?
    a
    1 reply · 2 participants
  • a

    Andrea Giuliano

    05/04/2021, 4:48 PM
    Hi guys, I was wondering if there is a way to write a function similar to let, where I can set some context to the lambda invoked. More specifically, I want to write a method that takes as a parameter a lambda and gives some context (an object) available to that lambda. Example:
    fun myFancyMethod(function: () -> O)
    so that a caller can use it this way:
    myfancyMethod{
      context.giveMeSomething() //context or it.context is available since it's set somehow from myFancyMethod
    }
    Is that feasible?
    p
    n
    +2
    30 replies · 5 participants
  • k

    Karlo Lozovina

    05/04/2021, 4:59 PM
    Has anyone noticed inconsistent behavior with
    SomeClass::class.sealedSubclasses
    method? Sometimes I need to
    gradle clean
    my project for it to return correct results. Happened with 1.4 and now with 1.5 RC versions
    a
    2 replies · 2 participants
  • d

    Dany

    05/04/2021, 9:40 PM
    class SeonApi {
        companion object {
            fun getEmailScore(emailInput: String): String {
                return "hello"
                var request: HttpRequest = HttpRequest.newBuilder()
                    .GET()
                    .uri(URI.create("<https://api.seon.io/SeonRestService/email-api/v2.0/>".plus(emailInput)))
                    .setHeader("X-API-KEY", @Value("\${seon_api_key}")) //***************complained: "Annotation class cannot be instantiated"
                    .build()
                var response: HttpResponse<String> = HttpClient.newHttpClient().send(request, BodyHandlers.ofString())
                return response.body()
            }
        }
    }
    This piece of code failed to compile and the debug. Had been spending 30 minutes debuging + googling without any success, anyone has a suggestion?
    v
    e
    8 replies · 3 participants
  • a

    Alessandro Tagliapietra

    05/04/2021, 10:45 PM
    Hi everyone, I'm trying to remove a duplication of this code:
    .filter { _key, value ->
                value.getTimestamp().isBefore(Instant.now().plusSeconds(600))
            }
    key
    is a string but I don't care what type it is
    value
    can be multiple types but all implement the getTimestamp method that returns an instant, so I've tried tried to create a file like this:
    interface DataWIthTimestamp {
        fun getTimestamp(): Instant
    }
    
    val filterFutureData: (key: Any, value: DataWIthTimestamp) -> Boolean = { _, value ->
        value.getTimestamp().isBefore(Instant.now().plusSeconds(600))
    }
    which doesn't work as it says
    Type mismatch.
    Required: Predicate<in String!, in Metric!>!
    Found: (Any, DataWIthTimestamp) → Boolean
    I know my implementation might not make sense 🙂
    n
    24 replies · 2 participants
  • i

    itnoles

    05/04/2021, 10:49 PM
    I noticed link is 404.
    v
    2 replies · 2 participants
  • j

    J6ey

    05/05/2021, 2:55 AM
    Hi I made a Kotlin project in Intellij. Kotlin files run just fine, however, when I create a java file I can't run it, giving me this error. Do I need to Edit Configurations for Java? I would assume you could run both..
    n
    a
    5 replies · 3 participants
  • p

    Patrick Ramsey

    05/05/2021, 3:49 AM
    So, I’m trying to make an honest effort to write code that doesn’t use exceptions to indicate expected (non-logic) errors, but I keep running into cases that exceptions solve very nicely and sealed classes do not. I’m finding it really hard to resist the urge to use exceptions, even though the fact that they’re unchecked means the type system doesn’t enforce error handling discipline on the caller. Examples of cases I don’t have good answers for: • Short-circuiting. I have to make a bunch of calls, the first of which that fails should stop execution of the rest. I’m not sure I see a good pattern for this with e.g. a Result type, other than wrapping each call with the same boilerplate to check the Result type and return early if appropriate. • Validation when instantiating a data class. Say I have a data class whose constructor does some validation on the passed-in values (say, one of its fields is an enum, but it’s being populated from an API call which returns a string). There’s no way that I can think of to signify failure in a constructor other than throwing an exception, since you can’t change the return type.
    n
    d
    124 replies · 3 participants
  • g

    gattytto

    05/05/2021, 5:31 AM
    hello, no #ide specific channel?
    t
    o
    2 replies · 3 participants
  • j

    jean

    05/05/2021, 5:44 AM
    I’m struggling understanding how to use in/out for generic types, here is what I’m trying to do :
    interface Executor<T, U> {
        fun isExecutable(): (T) -> Boolean
        fun execute(): suspend (U) -> Unit
    }
    
    class MyClass<T, U> {
    
         val executors = mutableMapOf<String, Executor<T, U>>()
    
        fun register(eventName: String, executor: Executor<T, U>) {
            executors[eventName] = executor
        }
    
        inline fun <reified V : U> register(executor: Executor<T, V>) {
            val eventName = V::class.toString()
            register(eventName, executor)
        }
    }
    I get the following error from the IDE
    Type mismatch. Required: Executor<T, U>, Found: Executor<T, V>
    U
    is a sealed class and
    V
    a subtype of that class. I did read the page about generic and “PECS” in the doc, but I still haven’t figured it out. Anyone knows what I need to change?
    e
    m
    3 replies · 3 participants
  • h

    huehnerlady

    05/05/2021, 6:31 AM
    Hi. Is there a reason why 1.5.0 is not yet officially released, even though it seems available? At least our dependabot finds it and tries to update all our versions. Which is a bit confusing if you cannot find releasenotes 😅
    ☑️ 1
    e
    r
    +3
    15 replies · 6 participants
  • h

    hho

    05/05/2021, 9:58 AM
    API docs are still only 1.4?
    s
    j
    4 replies · 3 participants
  • a

    Andrew Ebling

    05/05/2021, 11:35 AM
    I have an abstract class with two concrete subclasses containing implementations of
    fun myFunction()
    . The body of both implementations is different, but the last line is the same, calling a function in the abstract superclass. The common last line must be executed last. What is the most appropriate way to use Kotlin language features to refactor out the duplication?
    j
    f
    12 replies · 3 participants
  • c

    Cicero

    05/05/2021, 2:17 PM
    Dumb question, just updated to kotlin 1.5 and I cannot find the declaration of “listOf”. What’s up? I couldn’t find anywhere telling that it changed so I can only guess this is not usual. Anyone?
    t
    2 replies · 2 participants
  • p

    Pablo

    05/05/2021, 3:49 PM
    What's the idiomatic way to map a nullable list? Let's say I have this class
    class ProductModel {
       val productListModel: List<ProductListModel>? = null,
    }
    And I have the mapper like this
    fun map(input : ProductModel) : List<Product>{
      return input.productListModel?.map{Product(....)}.orEmpty()
    }
    Is there another elegant way? If the list is null or empty I should return an empty List of Product and if not, the list mapped
    t
    r
    +1
    5 replies · 4 participants
  • p

    Peter Ertl

    05/05/2021, 4:35 PM
    does anybody know how to generate .d.ts typescript definitions from my jvm project data / value classes? I read about (https://kotlinlang.org/docs/js-to-kotlin-interop.html#jsexport-annotation) but don’t get it if it works from an jvm style kotlin project.
    c
    4 replies · 2 participants
  • p

    Peter

    05/05/2021, 4:36 PM
    anyone having trouble with the new Duration API in 1.5?
    Expression 'seconds' cannot be invoked as a function. The function 'invoke()' is not found
    … literally looking at the seconds function in the Duration companion object 😳
    2 replies · 1 participant
  • p

    Peter Ertl

    05/05/2021, 4:45 PM
    does anybody know how to get the type (KType / KClass ?) of the embedded value in a value class?
    if (klass.isValueClass) {
      // TODO get type of embedded value for further processing
    }
    update - I think I found it:
    if (klass.isValue) {
      val ctor = klass.primaryConstructor ?: error("value class has no primary constructor")
      val valueType = ctor.parameters.firstOrNull()?.type ?: error("value class has no single parameter in constructor")
       // use it
    }
    If somebody knows a shorter way I would appreciate
    e
    14 replies · 2 participants
  • p

    Pablo

    05/05/2021, 5:23 PM
    Could be a better way of doing it without changing the signature of the model?
    fun createDummyProduct(number: Int = 1) = Product(id = "id$number", name = "name$number", title = "title$number")
    n
    e
    +1
    19 replies · 4 participants
  • p

    Paul Griffith

    05/05/2021, 8:32 PM
    Every time I try to update the Kotlin plugin this happens...any ideas? I'm on IJ Ultimate 2021.1.1; the 'Plugins' settings area doesn't suggest any updates are available
    j
    4 replies · 2 participants
  • s

    Shailan Patel

    05/05/2021, 8:41 PM
    does anybody know why https://pastebin.com/rdrdNDXn gives unresolved reference and https://pastebin.com/WSaThfvV doesn't and if it is possible to define a function within main(), why can't it be called too?
    n
    5 replies · 2 participants
  • p

    Philip Dukhov

    05/06/2021, 6:10 AM
    With 1.5 I can declare sealed subclasses outside of the parent class. With default sealed subclass I can access it easily by
    Sealed.Subclass
    , but is there a way to define new subclass in an other file but still be able to have it inside
    Sealed
    "namespace"?
    class Sealed.NewSubclass: Sealed()
    is not possible, but maybe there's an alternative? The reason why I need it is because I wanna generate some of sealed subclasses, and it's very convenient to have all subclasses under single namespace
    e
    s
    8 replies · 3 participants
  • h

    huehnerlady

    05/06/2021, 8:34 AM
    When I try to update my kotlin plugin in intellij it tries to download 1.3.72 not 1.5.0, even though it was correct in the overview. Any idea what I can do? I use Intellij 2021.1.1
    ☑️ 1
    c
    c
    +1
    23 replies · 4 participants
  • e

    Equilat

    05/06/2021, 9:02 AM
    Hi ! I'm discovering the new Jetpack Compose for web. I discovered the ability to write Stylesheets in Kotlin. For non Kotlin supported properties, there is the property(propertyName: String, value: StylePropertyValue). I would like to be able to add a font family from ttf file to my style. I know there is the @font-face in css but how could I manage to use it with the property(...) thing ?
    i
    1 reply · 2 participants
  • a

    alllex

    05/06/2021, 9:10 AM
    Hey, I have a question regarding bounds on generic types. ❓ In the Kotlin stdlib there this function:
    @SinceKotlin("1.3")
    @kotlin.internal.InlineOnly
    public inline fun <C, R> C.ifEmpty(defaultValue: () -> R): R where C : CharSequence, C : R =
        if (isEmpty()) defaultValue() else this
    You can call it and it works great. However, if I simply copy this function into my code (with intention to later have a slightly modified version), it simply does not compile:
    public inline fun <C, R> C.ifEmpty2(defaultValue: () -> R): R where C : CharSequence, C : R =
        if (isEmpty()) defaultValue() else this
    Produces error highlighting `CharSequence`:
    Type parameter cannot have any other bounds if it's bounded by another type parameter
    You can find the example here: https://pl.kotl.in/oGzbGuXah Why is this the case? Why can’t I use the same features used in stdlib?
    a
    y
    3 replies · 3 participants
  • v

    Vivek Modi

    05/06/2021, 10:51 AM
    Hi i want my dialog status bar like this as show in image. I asked in stack overflow also https://stackoverflow.com/questions/67415478/how-to-make-status-bar-inactive-in-custom-dialog
    :not-kotlin: 4
    1 reply · 1 participant
  • s

    Subodh Nijsure

    05/06/2021, 12:19 PM
    I created this issue here - https://youtrack.jetbrains.com/issue/KT-46508 but thought might get better guidance here. Consider main.kt and Attachment.java below, should the compiler have warned about self-assignment in extension method below?
    private fun ImageFile.toJavaAttachment(): JavaAttachment {
        return JavaAttachment().apply {
            /* Here imageName is correctly referenced */
            fileName = imageName
            /* compiler should have warned that this is a self-assignment? */
            updateTime = updateTime
        }
    }
    package org.kotllinlang.play
    
    import JavaAttachment
    
    data class ImageFile (
        val imageName: String,
        val imageType: Int,
        val updateTime: String
    )
    
    data class KotlinAttachment (
        var fileName: String = "default-kotlin-file-name",
        var updateTime: String = "default-kotlin-time"
    )
    
    fun main() {
    
        val image = ImageFile(
            imageName = "file.jpg",
            imageType = 1,
            updateTime = "this-is-updated-time-stamp")
    
        val javaAttachment = image.toJavaAttachment()
    
        val kotlinAttachment = image.toKotlinAttachment()
    
    
        println("Java attachment $javaAttachment")
    
        println("Kotlin attachment $kotlinAttachment")
    
    }
    
    private fun ImageFile.toKotlinAttachment(): KotlinAttachment {
        return KotlinAttachment().apply {
            fileName = imageName
            /* compiler correctly generates a self-assignment warning */
            updateTime = updateTime
        }
    }
    
    private fun ImageFile.toJavaAttachment(): JavaAttachment {
        return JavaAttachment().apply {
            /* Here imageName is correctly referenced */
            fileName = imageName
            /* compiler should have warned that this is a self-assignment? */
            updateTime = updateTime
        }
    }
    package org.kotllinlang.play;
    public class JavaAttachment {
    
        public String getFileName() {
            return fileName;
        }
    
        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
    
        public String getUpdateTime() {
            return updateTime;
        }
    
        public void setUpdateTime(String updateTime) {
            this.updateTime = updateTime;
        }
    
        private String fileName;
        private String updateTime;
    
        public JavaAttachment() {
            updateTime = "default-java-time";
            fileName = "default-java-file-name";
        }
    
        @Override
        public String toString() {
            return "JavaAttachment{" +
                    "fileName='" + fileName + '\'' +
                    ", updateTime='" + updateTime + '\'' +
                    '}';
        }
    }
    e
    6 replies · 2 participants
  • c

    CFIG

    05/06/2021, 2:58 PM
    Anyone met problems when upgrading
    org.jetbrains.kotlin.jvm
     to 
    1.5.0
    with subproject dependency?
    An exception occurred applying plugin request [id: 'org.jetbrains.kotlin.jvm', version: '1.5.0']
    > Failed to apply plugin 'org.jetbrains.kotlin.jvm'.
       > Gradle#projectsEvaluated(Action) on build 'boot' cannot be executed in the current context.
    I am using build.gradle.kts, It works fine with kotlin 1.4.31, but not 1.5.0.
    a
    1 reply · 2 participants
  • m

    Matěj Bystřický

    05/06/2021, 3:49 PM
    hi, just wanted to ask a quick question regarding multiple elvis operators. TLDR: is this correct?
    id = action.id ?: state.activeId ?: -1
    b
    n
    5 replies · 3 participants
Powered by Linen
Title
m

Matěj Bystřický

05/06/2021, 3:49 PM
hi, just wanted to ask a quick question regarding multiple elvis operators. TLDR: is this correct?
id = action.id ?: state.activeId ?: -1
b

Big Chungus

05/06/2021, 3:52 PM
Yes, it'll stop on first non-null value in the chain
m

Matěj Bystřický

05/06/2021, 3:54 PM
great, thank you! :)) And is this considered a good practice or is there a better way?
n

Nir

05/06/2021, 3:56 PM
Pretty sure this is fine for something this short
If you have ten ?: in a row.... then idk maybe at that point its' time to reconsider what's going on
b

Big Chungus

05/06/2021, 3:56 PM
Can't comment on good practices, but I'm using this everywhere where I need some default state. I also prefer returning null over throwing an exception, which ties in nicely with this pattern on consumer end
View count: 2