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

    Ayfri

    09/08/2021, 9:39 PM
    Hi, is there any way I can optimize this java code in Kotlin to have a something in one line ? I can't find anything right now, and I almost sure I have to do something with
    .let
    or similar functions but I can't come up with something
    j
    e
    +2
    • 5
    • 14
  • d

    dattq2303

    09/09/2021, 11:10 AM
    Hi, i'm having this kind of data class structure:
    abstract class AuthorizeSalesAdditionalSecurity {
        @SerializedName("lang")
        // Using like below is fine too
        // abstract val lang: String
        open val lang: String? = null
        @SerializedName("POSTransactionID")
        // abstract val POSTransactionID: String
        open val POSTransactionID: String? = null
    }
    data class CreditAuthorizeSalesAdditionalSecurity(
            @SerializedName("lang") override val lang: String,
            @SerializedName("POSTransactionID") override val POSTransactionID: String
    ) : AuthorizeSalesAdditionalSecurity() {}
    data class UnionPayAuthorizeSalesAdditionalSecurity(
            @SerializedName("lang") override val lang: String? = null,
            @SerializedName("POSTransactionID") override val POSTransactionID: String? = null
    ) : AuthorizeSalesAdditionalSecurity() {}
    I realize that I can use keyword "open" or "abstract" in AuthorizeSalesAdditionalSecurity and Kotlin accept both. Can someone explain for me the difference between 2 use case?
    m
    s
    • 3
    • 9
  • j

    Justin Tullgren

    09/09/2021, 4:34 PM
    Followup to that "NO" reply for inline classes. Is there java interop?
    j
    s
    • 3
    • 5
  • i

    Ivan Brko

    09/09/2021, 6:23 PM
    Hi everyone, been playing with the language some time ago and loved it, now i have an opportunity to write a small microservice in tech stack of my choice, so i planned using kotlin with ktor. Any pitfalls to be specially aware of? Also, what are other libraries/tools or compiler plugins that are must have with kotlin projects (things like linting, any special formatting libraries or something lke that)? Thanks for the help 🙂
    a
    • 2
    • 3
  • n

    nkiesel

    09/09/2021, 8:41 PM
    I am trying to serialize (and eventually deserialize) a
    koltin.time.Duration
    property of a data class in Kotlin 1.5.30 using Jackson 2.12.5. One immediate problem is that - because Duration is a value class - Jackson sees just a long value and thus serializes a
    Duration.seconds(10)
    as
    20000000000
    . This is obviously not what I want because it exposes the internal "use high bit to differentiate nano from milli". I tried to register a custom serializer which extends
    JsonSerializer<Duration>()
    using
    @JsonSerialize
    but that is ignored (presumably because Jackson just sees a long value). The only way I see right now is to have an explicit
    durationAsString
    property and keep that in sync with the
    duration
    property. Is there a better way? Note: I think I cannot use Kotlin serialization because this is part of a mixed Java/Kotlin project. But if I could: would that solve the issue?
    e
    • 2
    • 10
  • j

    Jan

    09/10/2021, 7:59 PM
    I have a mutableMap and two functions the queue function is getting called from different origins. But somehow the map is always empty if I modify it in these functions? Code:
    val buckets = mutableMapOf<String, RestClient.Bucket>()
    
    suspend fun queue(endpoint: String, task: suspend () -> HttpResponse): HttpResponse {
         println(buckets.size) //always 0
         //....
         send(endpoint, task)
    }
    
    private suspend fun send(endpoint: String, task: suspend () -> HttpResponse): HttpResponse {
         buckets[endpoint] = bucket
         println(buckets.size) //always one
    }
    z
    s
    • 3
    • 5
  • a

    Ayden

    09/11/2021, 1:42 AM
    As long as we pass the variable as a parameter, it will declare as
    val
    ?
    :yes: 1
    k
    e
    n
    • 4
    • 6
  • s

    suhas

    09/11/2021, 3:14 AM
    Best way to filter a list using other list? I want to filter a list of objects with list of ids. As of now, I am just doing this
    ids.forEach { id ->
       val person = persons.find { it.id == id}
       filteredList.add(person)
    }
    r
    e
    • 3
    • 5
  • e

    evkaky

    09/11/2021, 6:49 AM
    Hey guys! I was quite surprised with this code:
    repeat(3) {
       if (it == 0) return@repeat
       println("inside repeat")
    }
    it prints “inside repeat” twice instead of 0 times Why is that?
    e
    • 2
    • 4
  • d

    Daniel Branco

    09/11/2021, 10:01 AM
    Hey guys! I am at the very beginning of using Kotlin and understanding certain mechanics, if I have the following:
    data class Foo(
       var id: Int?, 
       var name: String = "bar", 
       var anotherVar
    )
    I thought I could have calls like
    Foo()
    or
    Foo(id=1)
    without needing to pass all the parameters to the constructor, am I wrong? Where can I read more about constructors in Kotlin?
    e
    s
    • 3
    • 6
  • c

    CLOVIS

    09/11/2021, 10:07 AM
    When creating a file with only top-level declarations, I know that there is an annotation so the automatically generated class isn't named “<File name>Kt”, but I can't remember which annotation it is, nor find the good search terms...
    e
    • 2
    • 5
  • i

    Ivan Brko

    09/11/2021, 10:40 AM
    is there a way to name case in
    when
    , so that i could write something like this:
    when (expression generating nullable){
      null -> handle null
      x    -> handle x for which compiler knows its not null anymore
    }
    j
    w
    • 3
    • 5
  • s

    suhas

    09/12/2021, 2:17 AM
    What the idiomatic way of doing this in Kotlin?
    if (mNotificationManager == null) {
                    mNotificationManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
     }
    e
    • 2
    • 1
  • d

    Daniel Branco

    09/12/2021, 5:40 PM
    Hey peepz, how are you? I have a question regarding Tests,
    @Nested
    ,
    inner
    classes,
    ParametrizedTests + MethodSource
    I have the following
    class MyServiceTest {
       data class TestData(...)
    
       @Nested
       inner class MyServiceSpecific{
          private fun prepareTestData() = Stream.of(...)
    
          @ParameterizedTest
          @MethodSource("prepareTestData")
          fun `GIVEN this example WHEN executing test THEN should run`(data: Testdata) {
             // EVERYTHING I WANT TO TEST
          }
       }
    }
    With this structure I get the following error
    Cannot invoke non-static method [private final java.util.stream.Stream... on a null target.
    How can I gave all this working, I am missing a glue probably
    b
    • 2
    • 3
  • l

    lesincs

    09/13/2021, 12:27 PM
    How to write an internal extension function for an existing class? See thread.
    j
    c
    • 3
    • 4
  • p

    PriNova

    09/13/2021, 12:27 PM
    Hello Community, At the moment, I have two functions, which are able to add and evaluate a lambda from a MutableList. Now, I want to save this List to a file in a human-readable format and later load them again and evaluate the lambdas. What is the best approach? Can I use JSON to save them? And edit them externaly. I want to avoid the ScriptEngine because I'm using linux aarch as host so kotlin/native did not work nor is the jna library compatible. Here is my code so far:
    typealias func = ()-> Unit
    
    @JvmField val command = mutableListOf<func>()
    
    fun main() {
    	
    	add {
    		val i =4
    		println("${i}")
    	}
    	
    	eval(command[0])
    }
    
    fun add(action: () -> Unit): Unit {
    	command.add(action)
    }
    
    fun eval(action: () -> Unit) {
    	action()
    }
    Thank you
    j
    • 2
    • 2
  • m

    Manuel Dossinger

    09/13/2021, 1:11 PM
    Not sure if this is the right channel, but: is there something new on that topic https://discuss.kotlinlang.org/t/what-is-an-idiomatic-way-to-create-a-read-only-wrapper-for-a-class/10929 ? I.e., I'd like to have a class
    data class MutableClass(var my1, var my2, var my3...)
    and a fitting
    data class ImmutableClass(val my1, val my2, val my3...)
    . So the only difference is, that all members of one class are
    var
    and the members of the other one are
    val
    and of course I don't want to write the list of members twice 🙂
    j
    e
    p
    • 4
    • 5
  • k

    Karlo Lozovina

    09/13/2021, 6:36 PM
    Given a class
    Base
    , Is there a way to run some code before and after every method call on Base's subclasses?
    a
    e
    +2
    • 5
    • 11
  • s

    Slackbot

    09/14/2021, 9:03 AM
    This message was deleted.
    d
    • 2
    • 1
  • a

    Anil Kumar

    09/14/2021, 4:30 PM
    With all the new advances in Kotlin, Flow, Coroutine etc. what is a good book/online course to get up to speed on latest and advanced Kotlin topics?
    s
    • 2
    • 1
  • b

    Brian Donovan

    09/15/2021, 6:43 PM
    why am I getting this?
    j
    • 2
    • 5
  • a

    Asq

    09/15/2021, 7:06 PM
    is this behavior expected of reified parameters?  Given (this is as simple as I could drive down my example):
    inline fun <reified R, reified S> reifiedGenericIsSame(r: R, s: S): Boolean = (r is S) && (s is R)
    interface FooBar<out A: Any, out B: Any>
    typealias FBOI<A> = FooBar<Int,A>
    typealias FBOS<A> = FooBar<String,A>
    and the following:
    open class Base<out A: Any, out B: Any>(val a: A, val b: B): FooBar<A, B> 
    
    class SpecialOfInt<out B: Any>(b: B) : Base<Int, B>(1, b)
    class SpecialOfStr<out B: Any>(b: B) : Base<String, B>("1", b)
    
    // val soitd: FBOI<Int> = SpecialOfInt(2)
    // val sostd: FBOS<Int> = SpecialOfStr(2)
    val soi = SpecialOfInt(2)
    val sos = SpecialOfStr(2)
    //
    // EDIT
    //
    val soitd: FBOI<Int> = soi
    val sostd: FBOS<Int> = sos
    then this holds:
    reifiedGenericIsSame(soi, sos) shouldBe false     // passes
    reifiedGenericIsSame(soi, sos) shouldBe true      // FAILS
    reifiedGenericIsSame(soitd, sostd) shouldBe false // FAILS
    reifiedGenericIsSame(soitd, sostd) shouldBe true  // passes
    which 🤞is VERY counterintuitive, as it appears a typealias (allegedly syntax sugar) is changing a result semantically. I suppose type erasure side effects may be invoked as the mechanics, but this question is about the intrinsic behavior. Could please anyone provide me with great kotlin wisdom?
    m
    • 2
    • 17
  • t

    Travis Griggs

    09/16/2021, 12:30 AM
    I have a polymorphic class tree. I want to enumerate a list of leaf classes, and evaluate each one with an argument and let each one tell me how suited it is for that context. The sorting and selection is straightforward to me. It's how to get abstract class side methods and a list of class instances that is confounding me.
    listOf<DragGesture>(DragCyclePositionGesture.class, DragMoveGesture.class, DragBeginGesture.class, DragEndGesture.class)
    is not legal. Number one, there needs to be way a way to make the template not be instances of DragGesture, but rather subtypes of DragGesture? Is that even specifiable? And the compiler isn't happy after the first .class either, i start getting all kinds of red after that. Am I supposed to use companions in this case? I'm not even sure how companions fit in the scheme of inheritance. 😕
    j
    • 2
    • 7
  • g

    Gopal S Akshintala

    09/16/2021, 12:51 PM
    How can I solve this? Gradle: 7.2, Intellij: 2021.2.2, Kotlin: 1.5.30, Kotlin IDE plugin: 212-1.5.30-release-409-IJ4638.7 I tried,
    rm -rf ~/.gradle/caches
    and Invalidate Caches and restart on Intellij
    a
    • 2
    • 1
  • k

    Karlo Lozovina

    09/16/2021, 3:10 PM
    What would be the equivalent in Java of
    Array<IntArray>
    ? I'm trying to store a 2D matrix of ints/floats in a compact way, would this Array of IntArrays be the way to go? Would that be equivalent to
    int[][]
    ?
    :yes: 4
    j
    y
    t
    • 4
    • 10
  • b

    Brian Donovan

    09/16/2021, 3:56 PM
    What does this mean, ViewBinding has type safety and null safety?
    j
    • 2
    • 2
  • n

    Norbi

    09/16/2021, 5:17 PM
    May I ask why this smart cast does not work? Thanks.
    fun <T : Any> isNotNull(value: T?): Boolean {
        contract {
            returns(true) implies (value != null)
            returns(false) implies (value == null)
        }
        return value != null
    }
    
    
    class ContractTest {
        @Test
        fun test1() {
            val a: String? = null
            if (isNotNull(a)) {
                println(a.uppercase()) // Works as expected: "Smart cast to kotlin.String"
            }
    
            val notNull = isNotNull(a)
            if (notNull) {
                println(a.uppercase()) // Compilation error: "Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?"
            }
        }
    }
    e
    • 2
    • 1
  • e

    elect

    09/17/2021, 8:45 AM
    how am I supposed to create a
    kotlin.time.Duration
    from something like
    d-hh:mm:ss
    ? Combining
    d.toDuration(DAYS) + hh.toDuration(HOURS)
    and so on? If yes, I find java
    Duration
    better in this regards, because you can parse it from a `String`:
    Duration.parse("..")
    j
    • 2
    • 11
  • d

    Danish Ansari

    09/17/2021, 2:07 PM
    what is the most efficient way to round
    Double
    up to certain decimal points, there is
    round()
    function in Kotlin but it always completely rounds up to 0 decimals? I want something like
    round(1.4999,decimalPrecision = 2) // 1.50
    j
    e
    c
    • 4
    • 29
  • v

    Viktor VAD

    09/18/2021, 11:17 AM
    Hello, I'm sorry if this has been asked before but, I'm mainly a web developer used to Ruby/Python/Js and new to the JVM/Kotlin/Android world; I'm looking for the mainstream package repositories like Rubygems, pip and npm. Are there such stable sources one should know and look at when searching for existing libraries? Thanks for your help!
    a
    e
    • 3
    • 3
Powered by Linen
Title
v

Viktor VAD

09/18/2021, 11:17 AM
Hello, I'm sorry if this has been asked before but, I'm mainly a web developer used to Ruby/Python/Js and new to the JVM/Kotlin/Android world; I'm looking for the mainstream package repositories like Rubygems, pip and npm. Are there such stable sources one should know and look at when searching for existing libraries? Thanks for your help!
a

andylamax

09/18/2021, 11:18 AM
maven-central is where most libs are published. But incase you tumble into Kotlin/JS, you are gonna need npm too
v

Viktor VAD

09/18/2021, 11:21 AM
Much appreciated @andylamax 🙏
e

edrd

09/19/2021, 1:25 PM
You may also want to look at awesome-kotlin. Hundreds of categorized projects/libraries there
❤️ 2
:kotlinnew: 2
View count: 4