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

    dave08

    12/08/2021, 12:26 PM
    This is probably wrong -- but how can I fix it without using kotlin-reflect?
    @ExperimentalStdlibApi
    inline operator fun <reified T : Any> SharedPreferences.getValue(owner: Any?, property: KProperty<*>): T {
        return when (val type = typeOf<T>()) {
            is Set<*> ->
                getStringSet(property.name.replace('_', '.'), emptySet()) ?: emptySet()
    
            else -> error("Invalid type")
        } as T
    }
    j
    r
    • 3
    • 16
  • d

    dave08

    12/08/2021, 5:01 PM
    If I have:
    class Foo { fun get(): Something }
    
    operator fun Bar.getValue(o: Any?, property: KProperty<*>): Something = Foo().get()
    
    val prop by Bar()
    Will the Foo instance get GCed?
    r
    • 2
    • 5
  • n

    neworldlt

    12/08/2021, 5:25 PM
    What is an idiomatic way of calculating the power of two for integers?
    j
    d
    +2
    • 5
    • 9
  • j

    Jasin Colegrove

    12/09/2021, 11:42 AM
    I want to use HikariCP. I have a bunch of DAOs that implement an interface for CRUD operations. What is the best way to pass around the DB connection to get the best use out of connection pooling?
    :not-kotlin: 1
    r
    • 2
    • 7
  • d

    d-static

    12/09/2021, 2:59 PM
    Im just here because one day I plan to work on some plugins, and I would rather use kotlin then java.
    m
    • 2
    • 2
  • a

    Alex

    12/09/2021, 5:59 PM
    Hi Guys, i kind of hit a road block while doing practice questions in code wars 1. I have a doubleArray which contains distances
    val x:DoubleArray = doubleArrayOf(0.0, 0.19, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25)
    the values are records every 1.5s distance travelled, in this case 0.0 is the starting point 0.19 is when the distance covered is recorded at 1.5 seconds mark after another 1.5 seconds the distance of 0.5 is recorded and so on. 2. I need to find the difference in distances as following
    0.0-0.19, 0.19-0.5, 0.5-0.75, 0.75-1.0, 1.0-1.25, 1.25-1.50, 1.5-1.75, 1.75-2.0, 2.0-2.25
    , i know how to use map(to double values or multiple then) but i don't know how to subtract from a preceded value with a previous value in an Array 3. you can refer to the full question if my explanation is not clear, i just need to find the difference in distances before i can proceed to do the next step, hope someone can help me on this 😅
    j
    p
    • 3
    • 10
  • b

    bbaldino

    12/10/2021, 10:18 PM
    I’m working with a java library that does something like this:
    class Foo {
        public static Foo.Builder Builder() { ... }
        public static class Builder { 
            public Builder() { ... }
        }
    }
    and i’m trying to call it from kotlin like:
    Foo.Builder()
    ...
    but i get complaints about ambiguity…i think because the helper type in
    Foo
    matches the class name (and therefore the constructor) exactly. does anyone know if there’s a way to disambiguate between the two from kotlin?
    r
    e
    • 3
    • 18
  • m

    martmists

    12/11/2021, 1:52 AM
    How do I get the fields and types of a class similar to how kotlinx.serialization does it? (using kotlin native)
    e
    • 2
    • 2
  • d

    Draget

    12/12/2021, 1:26 AM
    I am confused about secondary constructors. Kotlint avoid having an incomplete object constructed by forcing me to immediatly call the primary constructor. But I do not know how I can actually calculate the value for the primary constructor - I want to run code to calculate the value, that is the whole point of the second constructor. I can do it by using a function:
    private data class MyClass(val intVal: Int) {
        constructor(stringVal: String) : this(someFunction(stringVal))
    }
    
    fun someFunction(stringVal: String): Int {
        println("I can run some random code here")
        val foo = stringVal.reversed()
        return foo.toInt()
    }
    But how could I run code on the secondary constructor without using a function?
    e
    • 2
    • 13
  • c

    Camshaft54

    12/12/2021, 4:54 PM
    I have a question regarding elvis operators. If I want to print something then return from a function if the value is null, how would I do that with an elvis operator? I tried to do this, but I get an error saying that return is not allowed here:
    // getVal() returns a nullable value
    fun example() {
        val myVal = getVal() ?: {
            println("value is null")
            return
        }
    }
    j
    y
    f
    • 4
    • 5
  • c

    Colton Idle

    12/12/2021, 9:15 PM
    I had some hidden string formatting in one of my classes, and now that I want to write a test for it, I pulled it out into it's own class. It's your typical "Should I create a StringUtils class?" sort of question. Should I have
    class StringUtil {
        fun getInitialsFromName(name: String): String {
    or just create
    class InitialGeneratorService {
        fun get(name: String): String {
    Or should it be a companion or just make a string extension method (seems easily abused though) I'm definitely overthinking it, but approciate any advice
    b
    a
    • 3
    • 2
  • d

    dave08

    12/13/2021, 2:47 PM
    Lets say I have:
    interface Foo
    class Foo1 : Foo
    interface Bar {
       fun <T : Foo> baz(foo: T)
    }
    // This doesn't work, why? It IS derived from Foo... is there any way to do such a thing w/o taking in a Foo and casting it to Foo1?
    class Bar2 {
       override fun baz(foo: Foo1) = TODO()
    }
    e
    a
    j
    • 4
    • 22
  • m

    Miguel

    12/13/2021, 4:05 PM
    Hello everyone, can someone help me with this coroutine problem please:
    private suspend fun suspendFunction() : Boolean { ... }
    
    launch {
        val returnedValue = suspendFunction()
        if (returnedValue) anotherFunction() // this does not fire in the debugger
    }
    What am I doing wrong?
    j
    • 2
    • 1
  • m

    Matic

    12/13/2021, 8:12 PM
    Hi! I'm trying to use fragments for navigation.
    findNavController(R.id.nav_host_fragment_content_main).navigate(R.id.settingsFragment)
    I'm using this inside onOptionsItemSelected in the activity (I am trying to a settings fragment when I click on the button in ActionBar). Although this is working, if I click on the settings 5 times, I also need to click back 5 times. I am aware this is intended behaviour, but I can't seem to find how to avoid this.
    r
    • 2
    • 2
  • n

    nkiesel

    12/13/2021, 11:09 PM
    Groovy allows
    $
    in identifiers (e.g.
    A$B
    is a valid identifier). Kotlin allows quoted identifiers like ``A$B`` . But https://kotlinlang.org/spec/syntax-and-grammar.html#identifiers states that letters are "<any unicode character of classes LL, LM, LO, LT, LU or NL>" and that identifiers are "(Letter |
    '_'
    ) {Letter |
    '_'
    | UnicodeDigit} | `'`'` QuotedSymbol {QuotedSymbol} `'`'` ". Does that not mean that e.g. Ⅲ (aka \u2162) - which is part of unicode character class NL - should be a valid identifier? I just tried but the compiler does not like
    val Ⅲ = "roman 3"
    .
    e
    • 2
    • 4
  • m

    mcpiroman

    12/14/2021, 10:36 AM
    class Foo
    class Bar
    Why I can't do `Foo() == Bar()`but can
    Foo().equals(Bar())
    ?
    j
    • 2
    • 2
  • m

    martmists

    12/14/2021, 11:45 PM
    How would I go about implementing something like this:
    fun <R> convertTo(): R {
        return convertImpl()
    }
    
    fun convertImpl(): Int {
        // ...
    }
    
    fun convertImpl(): String {
        // ...
    }
    Is there an easy way to do it or will I have to just use a when statement and make R reified and add a branch for each implemented type?
    j
    • 2
    • 1
  • a

    Ayfri

    12/15/2021, 9:30 AM
    Hi, what is the better between
    data class Zone(x: IntRange, y: IntRange, z: IntRange)
    and
    data class Zone(x1: Int, y1: Int, z1: Int, x2: Int, y2: Int, z2: Int)
    ? And would it impact performances to use Ranges ? I only need like 50 zones maximum for my project
    1️⃣ 4
    m
    r
    y
    • 4
    • 6
  • a

    An Tran

    12/15/2021, 5:25 PM
    Do we have compose-web channnel?
    r
    m
    • 3
    • 2
  • c

    Colton Idle

    12/16/2021, 9:57 AM
    I have a simple app that makes a simple network request to get json. How do I convert that into an object without any 3rd party deps? I typically use gson or moshi for this sort of thing, but I don't think it's worth bringing in an entire library for this single network call. I know in java we used to just use some really bad Json apis, but I wonder if kotlin has anything else out of the box.
    h
    m
    t
    • 4
    • 8
  • p

    Philipp Dargel

    12/16/2021, 2:51 PM
    Hey, I'm getting started with kotlin and was wondering if there are any kotlin specific test assertion libraries like there is assertj for java? Builders seem like they would enable something interesting like
    assert("asdf") {
      hasSize { it isEq 4 }
    }
    k
    n
    +4
    • 7
    • 8
  • p

    Pablo Schmid

    12/16/2021, 7:50 PM
    Hello, I have a function that uses generic that I would like to mock using mockito.
    abstract class MyClass<T>(){
        abstract fun blocking(): T
    
    fun <R> execute(run: (T)->R, onError: ((e: Throwable)->R)? = null): R {
            return runCatching { run(blocking()) }.getOrElse{ e -> onError?.let { it(e) } ?: throw e}
    }
    }
    
    internal class MyClassImpl(): MyClass<String>() {
        override fun blocking(): String {
            return "something"
        }
    }
    I would like to mock the execute function in MyClassImpl that extends MyClass I usually mock functions as follows but it's not compiling as it can't infer the types
    private val myVariable = mock<MyClassImpl>().also {
            whenever(it.execute(any(), anyOrNull()).thenReturn(any())
        }
    Really appreciate the help.
    m
    • 2
    • 5
  • f

    Florian

    12/17/2021, 10:13 AM
    Don't know where to ask this question, but am I allowed to show this Slack channel on my Twitch live stream?
    🙌 1
    y
    a
    • 3
    • 3
  • o

    Orhan Tozan

    12/17/2021, 3:31 PM
    Updated to Kotlin 1.6.10, but now I'm getting this build error. How do I solve this?:
    java.lang.IllegalStateException: Symbol for kotlin.collections/mutableMapOf|-4813910536206556932[0] is unbound
    	at org.jetbrains.kotlin.ir.symbols.impl.IrBindablePublicSymbolBase.getOwner(IrPublicSymbolBase.kt:52)
    a
    • 2
    • 1
  • m

    Miguel Vargas

    12/17/2021, 10:33 PM
    Trying to come up with a test function to assert that every member of a list is of a specified type. This what I’ve tried
    fun assertListTypes(list: List<ParentType>, types: List<KType>) {
        assertEquals(list.size, types.size)
        types.forEachIndexed { idx, type ->
            assert(list[idx] is type)
        }
    }
    
    assertListTypes(list, listOf(typeOf<Class1>(), typeOf<Class2>()))
    But the compiler didn’t like the
    is
    check on the KType. Any ideas?
    m
    d
    • 3
    • 7
  • j

    Jonathan Briceño

    12/20/2021, 9:26 PM
    Hello guys, we are pretty new on our team with Kotlin and we are trying to understand coroutines, we have donde two different examples and one works and the other doesnt, maybe you guys can shed some light onto why one works and the other doesn't? We have been breaking our heads down here and no luck so far. Here's the example 1, working:
    c
    j
    • 3
    • 13
  • a

    Arnab

    12/21/2021, 11:53 AM
    Why is the compiler asking me for an
    else
    branch when I have covered all of the possible subclasses of
    Foo
    (sealed class) ? Was it always like this? I remember not having to implement an
    else
    branch before.
    r
    k
    • 3
    • 5
  • v

    Vitali Plagov

    12/21/2021, 1:13 PM
    I want to create an extension function that is using the
    apply{}
    function inside. Like:
    fun Foo.myFun() {
      bar.apply {
        this.doA()
        this.doB()
        this.doC()
      }
    }
    this
    here refers to the type of
    bar
    , not to the type of
    Foo
    How can I use the instance of
    Foo
    inside the
    bar.apply{}
    ?
    j
    • 2
    • 3
  • n

    Nikolay Lebedev

    12/21/2021, 2:35 PM
    I have a class with a
    MutableList
    as it's property. I want to iterate through this list and change values of elements. So I use
    listIterator
    and its
    set
    method to change element values. But when I exit a loop and print out a list from original object I see no changes. How do I change the original object?
    k
    • 2
    • 2
  • d

    dave08

    12/22/2021, 12:15 PM
    If I have:
    sealed interface Foo<R>
    object NoFoo : Foo<Nothing>
    data class SomeFoo<R> : Foo<R>
    
    // Is there any way this could work? (It doesn't... even though I don't use the R in NoFoo)
    val baz: Foo<Baz> = NoFoo
    r
    • 2
    • 12
Powered by Linen
Title
d

dave08

12/22/2021, 12:15 PM
If I have:
sealed interface Foo<R>
object NoFoo : Foo<Nothing>
data class SomeFoo<R> : Foo<R>

// Is there any way this could work? (It doesn't... even though I don't use the R in NoFoo)
val baz: Foo<Baz> = NoFoo
r

Rob Elliot

12/22/2021, 12:56 PM
Try using
<out R>
sealed interface Foo<out R>
object NoFoo : Foo<Nothing>
data class SomeFoo<out R>(val r: R) : Foo<R>
interface Baz

val baz: Foo<Baz> = NoFoo
d

dave08

12/22/2021, 1:09 PM
Thanks! I still have a bit of trouble with all this covariance etc... It seems in my case I had to use
in
with
Any
instead of
Nothing
...
r

Rob Elliot

12/22/2021, 1:40 PM
Without know your real use case it's hard to comment...
in Any
sounds like a pretty useless type.
d

dave08

12/22/2021, 1:43 PM
I don't really need it in that object... my use case is a bit complicated... I need that as a return type from a callback
() -> Foo<SomeType>
then, if I have a
SomeFoo
as a result of that callback, then I need it in something like
setResult(someFoo.value)
r

Rob Elliot

12/22/2021, 1:56 PM
Would this help?
sealed interface Foo<out R> {
  val value: R
}
object NoFoo : Foo<Nothing> {
  override val value: Nothing
    get() = error("unsupported")
}

data class SomeFoo<out R>(override val value: R) : Foo<R>
Slack is refusing to let me edit that...
val foo: Foo<String> = TODO()
if (foo is SomeFoo) {
  setResult(foo.value)
}
Alternatively, are you sure you aren't reinventing
kotlin.Result
?
d

dave08

12/22/2021, 5:01 PM
I'm not... I have three possibilities 1) Don't change anything, 2) Set a new value (including setting to null), 3) Set an exception (that was caught).
kotlin.Result
only has the last two...
I wonder if having that
<Any>
there is so bad... compared to the alternatives that are much more verbose...?
I can't edit my posts either @Alina Dolgikh [JB]... it seems like someone restricted editing posts on this slack...
Or maybe they're just having problems now?
View count: 1