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
android
  • o

    onirutlA

    03/03/2022, 12:15 PM
    Hi guys I need help are there any better way to refactor this code ? It's repository pattern, so i check data from db first if there is empty then fetch from network cache it and fetch the data from db and then return it if there is found just return it. so are there any better way to implement this ?
    override fun findUserByUsername(username: String): Flow<Resource<List<UserEntity>>> =
            localDataSource.findUserByUsername(username).map { fromDb ->
                when (fromDb) {
                    is FromDb.Empty -> {
                        when (val fromNetwork = remoteDataSource.findUsersByUsername(username)) {
                            is FromNetwork.Error -> Resource.Error(fromNetwork.message)
                            is FromNetwork.Success -> {
                                val userCache = fromNetwork.data.map { it.toEntity() }
    
                                localDataSource.insertUsers(userCache)
    
                                var userFromDb: Resource<List<UserEntity>> = Resource.Loading()
                                
                                localDataSource.findUserByUsername(username).collect {
                                    userFromDb = when (it) {
                                        is FromDb.Empty -> Resource.Error(it.message)
                                        is FromDb.Success -> Resource.Success(it.data)
                                    }
                                }
                                
                                userFromDb
                            }
                        }
                    }
                    is FromDb.Success -> Resource.Success(fromDb.data)
                }
            }.onStart {
                Resource.Loading<List<UserEntity>>()
            }.flowOn(dispatcher)
    e
    s
    • 3
    • 7
  • w

    Wishnuprathikantam

    03/04/2022, 1:43 PM
    Hi Guys, Any clues on how to handle com.squareup.moshi.JsonDataException to show an error message to the user without crashing the app unexpectedly. I don't have control over the API response so need to handle this gracefully and let the user know the app isn't compatible with the backend. I'm using Retrofit + OKHttp + Moshi. Any help is appreciated. Thanks.
    FATAL EXCEPTION: DefaultDispatcher-worker-3
        Process: com.myapp, PID: 18030
        com.squareup.moshi.JsonDataException: Required value 'fakeParam' missing at $
            at com.squareup.moshi.internal.Util.missingProperty(Util.java:660)
            at com.myapp.data.models.DeviceInformationJsonAdapter.fromJson(DeviceInformationJsonAdapter.kt:109)
            at com.myapp.DeviceInformationJsonAdapter.fromJson(DeviceInformationJsonAdapter.kt:22)
            at com.squareup.moshi.internal.NullSafeJsonAdapter.fromJson(NullSafeJsonAdapter.java:41)
            at com.squareup.moshi.JsonAdapter$2.fromJson(JsonAdapter.java:205)
            at retrofit2.converter.moshi.MoshiResponseBodyConverter.convert(MoshiResponseBodyConverter.java:45)
            at retrofit2.converter.moshi.MoshiResponseBodyConverter.convert(MoshiResponseBodyConverter.java:27)
            at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:225)
            at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:121)
            at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
    :not-kotlin: 3
    t
    s
    g
    • 4
    • 13
  • a

    Aaron Waller

    03/04/2022, 3:40 PM
    Anyone here who works with DigitalOcean Spaces? Currently trying to figure out how to upload images from device storage to my spaces. In all the tutorials I find they put their spaces-key and spaces-secret-key INSIDE the code which is then visible for everyone who decompiles the app 😅 I need a secure way
    :not-kotlin: 1
    e
    z
    • 3
    • 2
  • s

    Sergio C.

    03/04/2022, 4:57 PM
    Hello, anyone can create an Iterator to iterate over java.LocalTime without creating an infinite loop? I have this but this is looping forever... 😄
    class TimeIterator(
        startTime: LocalTime,
        private val endTimeInclusive: LocalTime,
        private val stepMinutes: Long,
    ) : Iterator<LocalTime> {
    
        private var currentTime = startTime
    
        override fun hasNext(): Boolean {
            return currentTime <= endTimeInclusive
        }
    
        override fun next(): LocalTime {
            val next = currentTime
            currentTime = currentTime.plusMinutes(stepMinutes)
            return next
        }
    }
    z
    e
    • 3
    • 12
  • v

    Vivek Modi

    03/04/2022, 9:32 PM
    Hey I am working in android kotlin. I have one base class and three child class which are inherited by base class. Shape.kt
    open class Shape {
        var data : List<Shape> = emptyList()
    }
    Three child class which are inherited through Shape class called Circle, Rectangle, Triangle. I create a variable called
    val shape = Shape()
    t
    • 2
    • 9
  • m

    Mahmoud

    03/06/2022, 5:15 AM
    Hi Guys, I got an interesting question about jetpack compose margin. As we can implement margin using padding or *Spacer*; Is it better to use padding instead? I said that because I now each composable is passed through compose, layout, drawing steps and I thought setting padding is just done on layout phase of that composable but Spacer will be passed in 3 phases separately. And Spacer creates extra Layout. Am I right?! #kotlin #compose
    c
    • 2
    • 2
  • l

    Lucca Beurmann

    03/07/2022, 1:51 PM
    hello everyone, does anyone knows how could i parse this date string: "2019-08-16 22:16:46.919688+00" to a dd/mm/yyyy format?
    :not-kotlin: 5
    r
    t
    h
    • 4
    • 7
  • v

    Vivek Modi

    03/07/2022, 5:14 PM
    Hey I am working in reyclerview. I want to fill children width with my screen. Does anyknow how to solve this in reyclerview in android.
    :not-kotlin: 5
    k
    • 2
    • 3
  • t

    Travis Griggs

    03/08/2022, 9:06 PM
    I supposed this is a Kotlin general question, but I just use it for Android so... Coming from Python and other environments, I've tended to prefer explicit this/self for variable/method reference. We had an interesting bug today. Here's a method:
    fun drop() {
       Plan.modifyRegistry { registry ->
          registry.filterKeys { oid -> oid != this.oid }
       }
       MCCommand.planDrop.oid(oid).sendToMC()
    }
    Plan objects have an
    oid
    instance variable, and store themselves in a mini companion singleton. I'm sure there are all kinds of counter suggestions for this architecture. I'm hoping we can leave those aside. Recently, I decided to when-in-rome... and try to embrace implicit this. I let someone go through and "clean up" all of the redundant this's. And so this code got changed:
    fun drop() {
       Plan.modifyRegistry { registry ->
          registry.filterKeys { oid -> oid != oid }
       }
       MCCommand.planDrop.oid(oid).sendToMC()
    }
    And suddenly the
    drop
    method went from removing itself, to cleaning the whole registry. I'm not sure what the point is, but I guess I'm surprised that the way that Kotlin plays fast and furious with variable name bindings doesn't cause others more issues like this. It certainly makes it harder for me to want to let go of explicit this.
    t
    c
    • 3
    • 5
  • a

    Android75

    03/10/2022, 5:34 AM
    #OT i need some help to use room automigration, is there some other dedicated android community ? i know here we are in kotlinlang.. so.. i. am sorry for OT
    k
    • 2
    • 1
  • n

    Nikolay Vlaskin

    03/10/2022, 12:37 PM
    Hi all. Who know, what profit i have if i add new line in the end file ? I see this setting but I don’t know if I need it ?
    :not-kotlin: 4
    z
    z
    l
    • 4
    • 11
  • v

    Vivek Modi

    03/10/2022, 9:07 PM
    Hey I working in kotlin android. The string is coming from server and it might be contains digit, character, empty string or null value. I want to convert that value in double because I want to compare value. So is there any better way to check that string only contain digit value and not empty or null in a kotlin way. The list is huge so I want a efficient way. Price.kt
    data class Price(
      var value: String? = null
    )
    main.kt
    val defaultValue : Double = 4.23
    val list = listOf(Price("2.33"), Price("fr23"), Price(""), Price(null), Price("4.23"), Price("12.23"))
    
    list.forEach{
       if(it == defaultValue){
          println("Found It")
       }
    }
    h
    t
    • 3
    • 17
  • b

    Breaker ACT

    03/11/2022, 3:45 PM
    Hi guys. Which your prefer way to invoke higher-order function, and why? Thanks
    fun hello(block: (String) -> Unit) {
    //1. block()
    //2  block.invoke()
    }
    1️⃣ 12
    v
    p
    • 3
    • 5
  • b

    Breaker ACT

    03/11/2022, 3:59 PM
    Kotlin syntax
    I am reading sample Clean Architecture code of Fernando Cejas. He implement as the images, how you think about this approach ? The pros: We can invoke the interface/abstract class which has been injected like a function call Ref
    a
    • 2
    • 19
  • e

    Enrico Saggiorato

    03/12/2022, 10:08 AM
    Hi, I recently wrote a backend with ktor, now I'm running it locally on http://localhost:8080 and trying to call it with retrofit, but I'm getting
    failed to connect to localhost/127.0.0.1:8080
    when usins "http://localhost:8080" as the base URL. How do I setup the thing?
    :not-kotlin: 4
    z
    l
    • 3
    • 2
  • c

    Chih Wei Lin

    03/12/2022, 4:53 PM
    Hi there Does any one know is there a lib/tool for "Generate screenshot with both dark and light theme for android app"
    :not-kotlin: 3
    z
    • 2
    • 3
  • k

    Kiprop Victor

    03/13/2022, 7:13 AM
    Hey, my project was running fine in android studio but now Gradle task :
    Execution failed for task ':buildSrc:compileKotlin'.
    with the following stack trace. I have matched the Kotlin version in the IDE with the project, what can cause this?
    • 1
    • 3
  • m

    Mehdi Haghgoo

    03/13/2022, 3:12 PM
    I get inconsistent values from ViewModel when I use it in another activity. Why is that? For example, I increment a value in ViewModel in activity 1 and I always get the value 0 in activity 2.
    :not-kotlin: 2
    b
    s
    • 3
    • 3
  • s

    StefMa

    03/14/2022, 1:55 PM
    Is there any benefit of using
    src/kotlin
    instead of
    src/java
    ? Or doesn’t it matter? Just a matter of style…?!
    k
    • 2
    • 1
  • a

    Andra Antariksa

    03/14/2022, 3:59 PM
    I got a unsolved problem about Compose Navigation about nested navigation. Please help me if you know the best practice for nested navigation in compose https://stackoverflow.com/questions/71410351/jetpack-compose-nested-navigation-and-bottomappbar
    s
    • 2
    • 1
  • v

    Vivek Modi

    03/14/2022, 4:34 PM
    Hey Guys, I have string which is coming from server.
    val string = "2.2"
    I want to show in textview like
    2.2
    . But if my string is
    2.00
    it will show
    2
    in my textview. How can I do this in kotlin efficient way?
    t
    a
    d
    • 4
    • 12
  • v

    Vladimir Tagakov

    03/16/2022, 1:12 AM
    Howdy! Can anyone help me explaining why is this happening:
    fun fact(): Observable<Any> = Observable.just(false)
            .distinctUntilChanged() // fails compilation
    vs
    fun fact(): Observable<Any> = Observable.just(false)
            //.distinctUntilChanged() // compiles just fine
    :not-kotlin: 2
    :kotlin: 4
    x
    p
    +3
    • 6
    • 10
  • a

    andodeki

    03/16/2022, 8:36 AM
    hi guys I have setup hilt two files at package name level for @HiltAndroidApp notation and MainActivity kotlin file with @AndroidEntryPoint notation. The app builds in android studio well but when I test it on device the app crashed when I remove the @AndroidEntryPoint notation from MainActivity kotlin file the app does not crash when tested on the physical device. What is the issue here
    LogcatError.txt
    :not-kotlin: 3
    c
    • 2
    • 2
  • a

    andodeki

    03/16/2022, 12:23 PM
    hey I was wondering why is a basic empty project for jetpack compose builds a big size apk compared to traditional XML app
    ✅ 1
    t
    g
    • 3
    • 2
  • c

    Chris Johnson

    03/16/2022, 8:48 PM
    Does anyone know how you could create a custom lint rule that would fail if it catches a certain function/function name being used anywhere outside a specified file?
    :not-kotlin: 2
    d
    • 2
    • 5
  • a

    Ali

    03/16/2022, 9:46 PM
    Hi anyone can save me here. This is working
    DecimalFormat.getIntegerInstance(new Locale("ar")).format(number);
    But this is not working
    DecimalFormat.getIntegerInstance(new Locale("bn")).format(number);
    I can see
    arabic
    number properly but for
    bangla
    its not working
    :not-kotlin: 3
    :java: 1
    g
    • 2
    • 3
  • t

    Tash

    03/16/2022, 10:56 PM
    Trying to follow the guidance of treating events/effects as state https://developer.android.com/jetpack/guide/ui-layer/events#views_1 For some things where you need to be truly imperative with views, such as
    webView.goBackward()/webView.goForward()
    , how do you encode them as state? They’re very event-like and need to happen just once given certain conditions, and could get complicated when state objects are `data class`es and you use
    .copy
    to update parts of state. More in 🧵
    b
    • 2
    • 3
  • r

    rkeazor

    03/18/2022, 3:28 AM
    Are prople seeing the coroutines Debugger option in the latest version of Android Studio Dolphin ?
    a
    s
    • 3
    • 14
  • a

    Abhilash

    03/18/2022, 9:29 AM
    I know there are a few of naming conventions for functions in compose. But is there any naming conventions I should follow for naming packages in compose
    a
    • 2
    • 1
  • h

    haoxiqiang

    03/18/2022, 10:48 AM
    I have a strange problem.
    @Parcelize
    data class Post(
    @SerializedName("topic_list")
    val topics: MutableList<Topic> = mutableListOf(),
    @SerializedName("tag_list")
    val tagList: MutableList<PostTag> = mutableListOf()
    )
    I build a android project with the kotlin-parcelize, if json with out topic_list/tag_list, I think it will be the default value which two empty list. but in last week. it’s generate by kapt without default value. after decompile:
    @SerializedName("media_list")
        @NotNull
        private List<Media> mediaList;
    Why….😅
    ✅ 1
    t
    • 2
    • 8
Powered by Linen
Title
h

haoxiqiang

03/18/2022, 10:48 AM
I have a strange problem.
@Parcelize
data class Post(
@SerializedName("topic_list")
val topics: MutableList<Topic> = mutableListOf(),
@SerializedName("tag_list")
val tagList: MutableList<PostTag> = mutableListOf()
)
I build a android project with the kotlin-parcelize, if json with out topic_list/tag_list, I think it will be the default value which two empty list. but in last week. it’s generate by kapt without default value. after decompile:
@SerializedName("media_list")
    @NotNull
    private List<Media> mediaList;
Why….😅
✅ 1
t

Tim Oltjenbruns

03/18/2022, 12:25 PM
So you mention JSON and Parcelize together, and I’m getting confused. I didn’t think those two were related.
So set me straight here - we are definitely talking about Parcels and not json right?
h

haoxiqiang

03/18/2022, 12:30 PM
yeah, now the data class post will failed when parcel write the topic list, because it generated with @NotNull but with init value. I want to get the real reason.
sorry, i have decompile the diff version. the parcelize generate the same code. It’s may be the gson config problem. I’ll find out why.
t

Tim Oltjenbruns

03/18/2022, 12:44 PM
I guess its possible that if Parcelize was giving you default values, that would affect Gson!
h

haoxiqiang

03/21/2022, 9:54 AM
In the weekend, i have find the reason. the gson library use an unsafe operator to create a obj. some related: https://github.com/google/gson/issues/1657 https://github.com/google/gson/issues/1550 https://github.com/google/gson/issues/1444 in consideration of the kotlin null/no-null is a very clear define. the gson is a bad impl. It took me an hour to switch to moshi. kotln frindly is important.
A parameterless constructor must be provided. If not, the gson will use a unsafe new instance api.
// is OK
data class A ( @SerializedName(“a”) val a:String=“”, @SerializedName(“b”) val b:Int=0 ) // is Failed data class A ( @SerializedName(“a”) val a:String, @SerializedName(“b”) val b:Int=0 )
View count: 28