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

    Manuel Pérez Alcolea

    09/25/2020, 10:55 PM
    Is it possible to specify the type of a function reference in the very same expression I'm referencing in? for example, instead of
    val function: ((Char) -> Unit) = ::println
    println(function)
    something like
    println(::println) // but this fails because it's ambiguous
    c
    • 2
    • 3
  • a

    Ayden

    09/26/2020, 4:14 AM
    Hi everyone. I always face difficulty to understand the context written in the documentation especially when the sentences contain of some terms. Examples like the Kotlin or Golang documentation. Does it mean I'm still not familiar with the terminology? How can I improve?
    n
    • 2
    • 2
  • r

    Rishit Dagli

    09/26/2020, 7:09 AM
    We are all geared up for our September Event going live in 90 minutes. We will have Carlos Mota and @Wajahat Karim speaking on Scoped Storage in Android and Building a Game 🎮 with Jetpack Compose. Register now if you haven't already at https://www.meetup.com/Kotlin-Mumbai/events/273000330/
    c
    • 2
    • 2
  • e

    Emmanuel Oga

    09/26/2020, 7:29 PM
    is there any logging solution for Kotlin able to perform a NOP through configuration? I'm currently using SLF4J, with calls like
    <http://logger.info|logger.info>("${PERFORM POTENTIALLY EXPENSIVE LOGGING OP}")
    , so even if I configure the logger to only log errors, the info call will still incur the cost of the expensive operation, with no message being logged. Would be nice to have it so the logging doesn't even happen at all unless I turn it on.
    n
    k
    +3
    • 6
    • 14
  • t

    TwoClocks

    09/27/2020, 12:34 AM
    anyone now is there is a slack for netty (not a kotlin questions obs)?
    m
    • 2
    • 1
  • h

    haroldadmin

    09/27/2020, 5:05 AM
    Does anyone know of a web-scraping library that supports Kotlin Multiplatform? I just need to parse
    <meta>
    tags on a webpage.
    ☝️ 2
    🇳🇴 1
    s
    • 2
    • 1
  • a

    Allan Wang

    09/27/2020, 9:29 AM
    Does kotlin have a specific function to convert from
    List<Char>
    to
    String
    or should we just use
    joinToString
    ? I’m trying to shuffle letters in a word and I’m doing so by
    String.toList().shuffled()
    a
    n
    +2
    • 5
    • 38
  • v

    vlad.minaev

    09/27/2020, 10:48 AM
    Anybody experiencing the same (infinite analyzing) in IJ Ultimate (2020.2.2)? Tried different version of Kotlin plugin
    IU-Kotlin.webm
    d
    t
    b
    • 4
    • 4
  • y

    Yan Pujante

    09/27/2020, 2:27 PM
    I would like to write a GUI desktop application for macOS and I want to have an icon in the top menu bar (like the time machine icon) as well as use the notification system. Can I do this in Kotlin? Do I need to use Kotlin native?
    s
    • 2
    • 12
  • m

    Michael de Kaste

    09/28/2020, 9:04 AM
    considering the following code:
    val hasMyPredicate = someObject.someField.hisField.finalField != null
    val someOtherBoolean = extensiveFunction()
    when{
        hasMyPredicate && someOtherBoolean -> {...}
        !hasMyPredicate && someOtherBoolean -> {...}
        !hasMyPredicate && !someOtherBoolean -> {...}
        hasMyPredicate && !someOtherBoolean -> { val value = someObject.someField.hisField.finalField //value is nullable here, but the precondition made sure that it isn't }
    }
    How can I reference a deep inner value to be non-null and then when accessed it is autotyped to be non-null I absolutely hate using !! and especially error("...") if the chain of access calls are all on non-settable values (they are all val)
    u
    • 2
    • 1
  • v

    vio

    09/28/2020, 12:01 PM
    hi all! I'm having the following code:
    object A {
    	val a = ...
    
       object B {
        	val b = ...
       }
    }
    and I'm accessing b like this:
    A.B.b
    (which is what I need) but I would like to move class B into another file, and still acces
    b
    the same way and I can't find the right way to define it I would like to have something like bellow (this is not a valid code):
    object A.B {	
        val b = ...
    }
    Is there a way to get something similar? Thank you in advance!
    a
    • 2
    • 2
  • b

    Ben Toofer

    09/28/2020, 3:04 PM
    Hey I’m coming from Typescript and Im trying to figure out how to “translate” some typings into Kotlin. I currently have this in Typescript code snippet where I am defining an interface general (
    Version
    ) which can be extended to defined a specific object structure. I then have a defined type
    VersionDefinition<V extends Version>
    which has a simple data structure to it but it is restricted to implement the keys of the specified version (
    [x in keyof V]
    )
    // Defining a map interface of a key type string and value type of any
    interface Version {
     [key: String]: any
    }
    
    // Defining an object type that enforces the implementation of the specified version (V)
    type VersionDefinition<V extends Version> = {
     [x in keyof V]: {
       description: String,
       headerName: FakeHeader,
     }
    }
    // Version 1 interface
    interface Version1 extends Version {
     foo: Integer,
     bar: Integer,
     ...
    }
    
    // Version 1 implementation
    const VERSION_1_DEFINITION: VersionDefinition<Version1> = {
     foo: {
       description: "Bar description",
       headerName: FakeHeader.FOO
     },
     bar: {
       description: "Bar description",
       headerName: FakeHeader.BAR
     }
     ...
    }
    I know I can create the
    Version1
    interface as a data class in Kotlin but my question then is there a way to create something similar to the
    VersionDefinition<V extends Version>
    where it enforces you to implement the keys of some interface, data class or map?
    m
    • 2
    • 1
  • b

    Brian Dilley

    09/28/2020, 8:11 PM
    to what advantage?
    p
    j
    • 3
    • 3
  • w

    william

    09/29/2020, 1:54 AM
    i'm trying to write my own logging utility. is there anyway to use reified functions / extension functions to automatically get the calling classes name? something like
    // usage
    MyLogger.log("foo")
    
    // impl
    inline fun <reified T : Any> T.log(msg: String) {
      // ...
      val caller = T::class.simpleName
    }
    n
    n
    +5
    • 8
    • 16
  • c

    CLOVIS

    09/29/2020, 12:57 PM
    What is the Kotlin team focusing on more? JS or WASM? I wonder which one should be preferred for multiplatform applications
    b
    s
    +2
    • 5
    • 10
  • v

    Vera van Mondfrans

    09/29/2020, 2:13 PM
    Hey hey, I’m doing something I feel should be much easier than how I’m doing it. I have an abstract class with some basic storage logic for domain entities:
    abstract class ESGenerics<IDType : DomainID, EntityType : Entity>(
      private val elasticsearchClient: RestHighLevelClient,
      private val objectMapper: ObjectMapper
    ) {
       // ...
    }
    All Entity classes has an ID member that should always extend DomainID, so I made this:
    interface Entity {
      val id: DomainID
    }
    These functions need EntityType and IDType as types for arguments. Now I feel like I shouldn’t have to pass the IDType to ESGenerics. After all, the EntityType always has an ID field with the correct type. But I can’t figure out how to access the type of EntityType’s ID member in a function declaration. I’d like to rewrite it from:
    fun getByIDs(ids: List<IDType>): List<EntityType> {
    To:
    fun getByIDs(ids: List<EntityType::id>): List<EntityType> {
    How can I do that?
    n
    • 2
    • 71
  • n

    nanodeath

    09/29/2020, 2:50 PM
    are there other multiplatform testing libraries out there, or is it basically just
    kotlin.test
    ? I miss AssertJ...
    s
    b
    +2
    • 5
    • 21
  • s

    Sulav Timsina

    09/29/2020, 3:26 PM
    #general Since Kotlin Multiplatform is all over news, what do you have your say about it? Is it good to learn it?
    🙄 2
    a
    • 2
    • 1
  • n

    Nir

    09/29/2020, 3:56 PM
    given that
    plus
    has a single element overload, what's the reason for plusElement existing?
    n
    i
    t
    • 4
    • 16
  • c

    cfleming

    09/29/2020, 9:03 PM
    If I have a constant like:
    const val DEBUG = false
    and then code like:
    if (DEBUG) {
      println("Addthread: $thread")
    }
    If
    DEBUG
    is set to false, will the `println`s be totally compiled out of the class file?
    n
    e
    v
    • 4
    • 11
  • b

    BramYeh

    09/30/2020, 1:18 AM
    https://medium.com/androiddevelopers/busting-android-performance-myths-d85ae1d87f22
    😂 1
    n
    s
    w
    • 4
    • 9
  • t

    Thiago

    09/30/2020, 12:35 PM
    I need block an OkHttp Interceptor to wait other async operation return another Response with the same Chain. Is runBlocking the better way to do that? Below is my current implementation. It's working but I'm in doubt if there is a better way without block many parallel requests.
    internal class CustomInterceptor(
        private val processor: Something
    ) : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val response = chain.proceed(chain.request())
            // FIXME: is this fine? Can this throw Socket timeout?
            return runBlocking(Dispatchers.Default) {
                processor.suspendUtilHaveAnotherResponseOrThrow(response, chain)
            }
        }
    }
    z
    • 2
    • 1
  • r

    Roland Yeghiazaryan

    09/30/2020, 12:54 PM
    Anyone else has an issue with formatting 'when' statements after upgrading to kotlin 1.4.0+? There is a setting
    Align when branches in columns
    which is broken for us after the update. Please see the screenshots for actual and expected behavior.
    👀 1
    y
    m
    • 3
    • 8
  • e

    Emmanuel Oga

    10/01/2020, 7:40 AM
    Hi. I have some code that writes to an
    OutputStream
    , and some code that needs that data but wants to read from an
    InputStream
    . I came up with this but I was wondering if maybe thre's a more straightforward solution:
    /**
     * Pipe output to an input stream. Uses a thread to write from output to input.
     * See: <https://stackoverflow.com/questions/5778658/how-to-convert-outputstream-to-inputstream>
     */
    fun ByteArrayOutputStream.asInputStream(): InputStream = PipedInputStream().also { istream ->
        PipedOutputStream(istream).let { ostream ->
            Thread { ostream.use { writeTo(ostream) } }.start()
        }
    }
    Thanks!
    v
    • 2
    • 6
  • x

    Xabier Gorostidi

    10/01/2020, 10:00 AM
    Hello, does anybody know why the first timeout coroutine is not being cancelled when the second one gets a results and forces all children cancellation of the context?
    class Test(val callbackWork: CustomCallbackWork) : CoroutineScope {
        private var job = Job()
        override val coroutineContext: CoroutineContext
            get() = <http://Dispatchers.IO|Dispatchers.IO> + job
    
        fun start() : Flow<Unit> {
            return channelFlow {
                launch {
                    delay(5000)
                    logger().d("After delay, isActive: $isActive")
                    close()
                }
    
                launch {
                    callbackWork.apply {
                        onSuccess = {
                            offer(Unit)
                            coroutineContext.cancelChildren()
                        }
                        onError = {
                            offer(Unit)
                            coroutineContext.cancelChildren()
                        }
                    }
                }
            }
        }
    }
    The log is printed (obviously displaying
    isActive=true
    ) after 5 seconds even though
    onSuccess
    is triggered before that delay. However, if I get the reference of the first Job and cancel it below, it works perfectly. What's wrong in the code?
    z
    • 2
    • 9
  • a

    Andrea Giuliano

    10/01/2020, 12:44 PM
    Hi guys, newbie question about kotlin comparison. I want to create a data class that has some fields. And I want to make this comparable. I know I can implement Comparable interface. Is there facility in kotlin to implement the compareTo function? I see there is a compareValuesBy I can use but it wanted to avoid to do compareValuesBy for every field. What am I missing?
    s
    v
    +2
    • 5
    • 116
  • k

    Kash Kabeya

    10/01/2020, 5:19 PM
    Hi guys, I work for a banking company and we are looking at Kotlin multiplatform but a stumbling block is code obfuscation... has anyone managed to solve this issue? we use arxan for both iOS and Android
    n
    f
    +3
    • 6
    • 15
  • c

    Cole K

    10/01/2020, 5:56 PM
    Hello!! I’m trying to get an objects class by its class name and its throwing a class not found exception
    Class.forName("com.mystuff.stylopoc.core.Features.Login")
    I think its worth noting that the object, Login, is internal to a sealed class, Features Any ideas?
    s
    n
    e
    • 4
    • 6
  • g

    groostav

    10/01/2020, 9:57 PM
    really simple programming question: whats the most elegant way to pad out a list with its own elements until a given size is reached? eg:
    conciseExpr(listOf("A", "B"), 5) //output: [A, B, A, B, A]
    conciseExpr(listOf("A", "B"), 2) //output: [A, B]
    conciseExpr(listOf("A", "B"), 1) //output: [A]
    you are gaurenteed that the input list is non-empty so far I'm working with
    val output = inputList
            .let { partial -> (0 until 1+(inputTargetSize / partial.size)).map { partial }.flatten() }
            .take(inputTargetSize)
    but i feel like
    0 until 1+expr
    is cloogy
    n
    n
    e
    • 4
    • 27
  • p

    Pablo

    10/02/2020, 11:54 AM
    Is there any Kotlinian way to :
    class Dog(val name: String, val age: Int, val owner:Owner = Owner.Jhon)
    Then I have another class that creates that Dog as :
    fun getOwner() : Owner {
     return if (something is true) Owner.Peter else Owner.Jhon
    }
    And this is what I'd like to improve, I see that I have this
    Owner.Jhon
    duplicated, because is default value already is there any way to avoid this Owner.Jhon from getOwner?
    s
    s
    • 3
    • 2
Powered by Linen
Title
p

Pablo

10/02/2020, 11:54 AM
Is there any Kotlinian way to :
class Dog(val name: String, val age: Int, val owner:Owner = Owner.Jhon)
Then I have another class that creates that Dog as :
fun getOwner() : Owner {
 return if (something is true) Owner.Peter else Owner.Jhon
}
And this is what I'd like to improve, I see that I have this
Owner.Jhon
duplicated, because is default value already is there any way to avoid this Owner.Jhon from getOwner?
s

spand

10/02/2020, 12:00 PM
You can extract default owner to companion object and use it both places
s

Stephan Schroeder

10/02/2020, 1:49 PM
You write Then I have another class that creates that Dog as : but what follows is a function that creates an Owner, so I’m a bit confused. What I can say is that
getOwner
only contains a single expression, so you should do the single-line version:
fun getOwner() : Owner = if (something is true) Owner.Peter else Owner.Jhon
you can even drop the
: Owner
return-type if you want. Another thing is that I normally don’t see Java-type
getSomething
functions since you can define a more koliny dynamic
something
-property:
val owner: Owner
  get() = if (something is true) Owner.Peter else Owner.Jhon
if the value is only initialized once, you could of course change it to a traditional property:
val owner: Owner = if (something is true) Owner.Peter else Owner.Jhon
.
getOwner
isn’t a method of
Dog
, is it? Because you can already access the owner property of dog directly (since it’s not private).
val dogOwner = dog.owner
View count: 3