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

    Quanta

    11/09/2021, 3:43 PM
    Hello everyone This code throws an internal compiler error at the time of building, I think it's a bug in Kotlin compiler ?
    @Composable
    fun Reproduce() {
        var currentRoute: String? = null
        val expr = currentRoute != null && shouldShowBottomNav(currentRoute)
    }
    
    @Composable
    fun shouldShowBottomNav(currentRoute: String): Boolean {
        return true
    }
    It only happens when the functions are annotated with
    @Composable
    so probably related to Jetpack compose I was only able to reproduce the error on the same project though, it does not really happen when I start a new project and try the same. I have tried: Clean building, invalidating IDE cache, deleting files under
    ~/.android
    and
    ~/.gradle
    to clear those caches but it always gives me same result Here is the traceback from android studio: https://pastebin.com/i5BkEDBU
    c
    l
    +3
    • 6
    • 10
  • d

    Dheeraj Singh Bhadoria

    11/10/2021, 4:41 AM
    Hello everyone, I want to convert my existing app ( Written in kotlin ) to KMM for both Android and iOS without writing code in swift/objective-c. Is it possible to write the UI as well as business logic in kotlin for both Android and iOS. Is it possible with kotlin only ?
    🇳🇴 4
    c
    g
    • 3
    • 8
  • w

    wck

    11/10/2021, 5:17 AM
    org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't inline method call: remember { mutableStateOf("test") }
    a
    • 2
    • 1
  • s

    Sololo

    11/10/2021, 1:35 PM
    why ?
    d
    e
    • 3
    • 3
  • z

    Zoltan Demant

    11/10/2021, 1:51 PM
    Does anyone by any chance know why I keep seeing crashes related to
    Bad notification posted from package: x Couldn't create icon: StatusBarIcon
    on Android 8.1? Im not using any vector-drawables. The icons are all white icons in
    .png
    files.
    :not-kotlin: 2
    • 1
    • 1
  • k

    K Merle

    11/10/2021, 5:05 PM
    Is there a recommended way to abstract data class?
    • 1
    • 1
  • s

    Sergio C.

    11/10/2021, 5:16 PM
    Hello, Do I need any special dependency to use SharedFlow? I'm checking some examples but I get an error when creating MutableSharedFlow with parameters.
    MutableSharedFlow<Unit>(replay = 0)
    :kotlin-intensifies: 1
    j
    • 2
    • 4
  • a

    AmrJyniat

    11/11/2021, 7:07 AM
    New android projects doesn't include
    maven { url "<https://jitpack.io>" }
    by default, is there any documentation for this change?
    :not-kotlin: 2
    v
    m
    • 3
    • 4
  • h

    Hovhannes

    11/11/2021, 9:36 AM
    Hello, I've a question related to webview performance. In Webview loading of sites is very slow and some contents shows not properly.  What mistake did I make?  Thanks in advance.
    private fun webViewSettings(url: String) {
    
        activityWebBinding.webView.settings.apply {
            javaScriptEnabled = true
            domStorageEnabled = true
            builtInZoomControls = true
            displayZoomControls = false
            javaScriptCanOpenWindowsAutomatically = true
            cacheMode = WebSettings.LOAD_DEFAULT
            setAppCachePath(applicationContext.cacheDir.absolutePath)
    
            defaultZoom = WebSettings.ZoomDensity.FAR
            loadWithOverviewMode = true
            useWideViewPort = true
            allowFileAccess = true
            allowContentAccess = true
            setSupportZoom(true)
            layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
    
            setRenderPriority(WebSettings.RenderPriority.HIGH)
            mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
    
            setSupportMultipleWindows(true)
        }
    
        activityWebBinding.webView.apply {
            if (Build.VERSION.SDK_INT >= 22) {
                setLayerType(View.LAYER_TYPE_HARDWARE, null)
            } else {
                setLayerType(View.LAYER_TYPE_SOFTWARE, null)
            }
            scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
            isScrollbarFadingEnabled = true
            setBackgroundColor(Color.TRANSPARENT)
            loadUrl(url)
        }
    }
    :thread-please: 3
    :not-kotlin: 2
    s
    • 2
    • 1
  • m

    Mahdi Shahpuri

    11/13/2021, 9:47 AM
    Hi could you please hire me 😭
    :not-kotlin: 6
    l
    • 2
    • 1
  • p

    PanicMonster

    11/14/2021, 6:43 AM
    having problems understanding these function params. i have very little knowledge about callback fun. can someone explain how these params are working?
    fun loadBlogArticles(onSuccess: (List<Blog>) -> Unit, onError: () -> Unit) {
        val request = Request.Builder()
                .get()
                .url(BLOG_ARTICLES_URL)
                .build()
    
        executor.execute {
            runCatching {
                val response: Response = client.newCall(request).execute()
                response.body?.string()?.let { json ->
                    gson.fromJson(json, BlogData::class.java)?.let { blogData ->
                        return@runCatching blogData.data
                    }
                }
            }.onFailure { e: Throwable ->
                Log.e("BlogHttpClient", "Error loading blog articles", e)
                onError()
            }.onSuccess { value: List<Blog>? ->
                onSuccess(value ?: emptyList())
            }
        }
    }
    r
    e
    • 3
    • 2
  • s

    Sololo

    11/15/2021, 8:31 AM
    public abstract void onResult(@NonNull List<Value> data, int position, int totalCount,
            @Nullable Key previousPageKey, @Nullable Key nextPageKey);
    what does that ‘totalCount’ mean? use the jetpack’s paging2.
    :not-kotlin: 1
    s
    • 2
    • 1
  • r

    Rasmus Hummelmose

    11/15/2021, 8:13 PM
    Hi all, Having a small challenge sorting a list, it is placing null values before successfully compared values. I don’t really get it. Please look here: https://pl.kotl.in/8iQlwp1t7
    e
    • 2
    • 3
  • m

    Mehdi Haghgoo

    11/15/2021, 9:07 PM
    I don't understand what these lines inside when do. Would someone mind explaning a bit to me?
    override fun toString(): String {
        return when (this) {
            is Success<*> -> "Success[data=$data]"
            is Error -> "Error[exception=$exception]"
        }
    }
    This is from the template Login Activity in Android Studio. What is Success<*> and what is "Success[data=$data]"?
    l
    p
    +2
    • 5
    • 6
  • h

    haris mehmood

    11/16/2021, 11:36 AM
    Hi, how to remove item at specific position in RecyclerView using paging library 3?
    :not-kotlin: 6
    m
    • 2
    • 4
  • r

    Rajput Art Studio

    11/16/2021, 5:50 PM
    Hii friends anyone can help to implement paging library with retrofit, room, flow and dagger hilt. Any best example for learn paging library
    k
    • 2
    • 4
  • a

    Ashu

    11/17/2021, 7:01 AM
    Is there a function in kotlin like trimIndent or trimMargin to replace all whitespaces and all line breaks from a string template with a single space? If not, how can one achieve this? With regex?
    k
    j
    • 3
    • 3
  • e

    Elias Estrada

    11/17/2021, 12:27 PM
    Hi quick question, has anyone made an app for a Polestar vehicle? If so, could you point me in the right direction or dm me a few docs to take a look at, I would appreciate the help. Thanks!
    :not-kotlin: 4
    j
    • 2
    • 1
  • t

    tursunov abdulbois

    11/17/2021, 2:20 PM
    Hi, guys. I have AuthtenticationInterceptor to add token into header of request. In overrided intercept function it uses runBlocking builder to get token (token is obtained as flow object. Its repository implements PreferencesDataStore). I should replace runBlocking builder to other proper implementation. Because using runBlocking builder in production code is not good practice. Any sugestions?
    @Singleton
    class AuthenticationInterceptor @Inject constructor(profileRepository: ProfileRepository, @ApplicationScope coroutineScope: CoroutineScope) :
        Interceptor {
    
        private val tokenFlow: Flow<String?> = profileRepository.getProfileToken()
            .stateIn(coroutineScope, SharingStarted.Eagerly, null)
    
        override fun intercept(chain: Interceptor.Chain): Response {
            val requestBuilder = chain.request().newBuilder()
            val token: String? = runBlocking { // this line should be changed
                tokenFlow.firstOrNull()
            }
            token?.let { requestBuilder.addHeader("Authorization", it) }
            return chain.proceed(requestBuilder.build())
        }
    }
    c
    • 2
    • 1
  • k

    Kamo Spertsyan

    11/18/2021, 7:21 AM
    Is there any linters for Dokka checking that every public method of class is commented or something like that?
    p
    • 2
    • 2
  • m

    Marko Novakovic

    11/18/2021, 10:15 AM
    coroutines + espresso In
    Fragment.onCreate
    am calling
    lifecycleScope.launch { ... }
    .
    …
    😄 is something I need to verify but espresso test is not waiting for it so it’s not deterministic, sometimes it fails and sometimes it passes. how can I make espresso test to wait for
    …
    inside
    launch {}
    to finish? is
    IdlingResources
    what am looking for? ideally I would move all of that into
    ViewModel
    and not deal with it in the
    Fragment
    but currently it’s not up to me 😕
    g
    p
    • 3
    • 8
  • s

    Sergio C.

    11/18/2021, 11:05 PM
    Hi, How can I create this extension function sortByStringValue? I have a list that can contain strings or numbers as strings. Sorting won’t work correctly if the string contain numbers. If I have a selector that can return String or Double it’s not accepted. Any good workaround?
    val list = mutableListOf<String>("10", "0.1", "0.01", "1")
            list.sortBy { // default kotlin in-place sorter
                it
            }
            list.sortByStringValue {
                if (it.toDoubleOrNull() == null) {
                    it
                } else {
                    it.toDouble()
                }
            }
    j
    • 2
    • 16
  • n

    Nabeel

    11/19/2021, 5:03 AM
    Hi all, Getting java.lang.reflect.InvocationTargetException (no error message) when adding @AndroidEntryPoint annotation to subclass of FirebaseMessagingService class Code in 🧵
    :not-kotlin: 3
    • 1
    • 1
  • s

    spierce7

    11/21/2021, 7:40 PM
    Can we stop poking people for
    Not Kotlin
    ? Who cares? Are we trying to be like stack overflow? People need places to ask questions that they have, and chat communication is far more accessible than posts. This is probably the only chat / slack community that many developers are a part of, especially when it comes to Android.
    :not-kotlin: 6
    👍🏽 1
    👍 8
    👎 10
    e
    r
    +2
    • 5
    • 11
  • m

    Marko Novakovic

    11/22/2021, 12:16 PM
    am trying to handle saving state across process death using
    SavedStateHandle
    and I want to introduce
    Flow
    like this:
    class MyViewModel<State>(
        private val savedStateHandle: SavedStateHandle,
        initialState: State,
    ) : ViewModel() {
        private var _state by mutableStateOf(initialState)
        val state: State
            get() = _state
    
        init {
            viewModelScope.launch {
                savedStateHandle.getFlow(STATE, initialState)
                    .collect { _state = it }
            }
        }
    
        fun updateState(reducer: State.() -> State) =
            savedStateHandle.set(STATE, state.reducer())
    
        companion object {
            private const val STATE = "state"
        }
    }
    it crashes my tests but when I do regular
    get
    ,
    set
    on
    savedStateHandle
    tests work fine. both work great when I run in on emulator or real device but every single test crashes. any help?
    :stackoverflow: 1
    👍 1
    v
    • 2
    • 3
  • v

    Vivek Modi

    11/22/2021, 2:30 PM
    Hey, I want to restrict zero at the beginning of text input when the user type. So How it would be possible to restrict to enter zero at the be beginning, but the user can enter in the middle of the text. For example Not enter Zero at beginning
    0111 user will not allow displaying in edit text. only 111 is allowed
    Allow zero at middle
    1101 it can allow zero in middle.
    :not-kotlin: 4
    r
    r
    e
    • 4
    • 6
  • t

    TarunY

    11/22/2021, 3:19 PM
    HI Guys, I have Main fragment which consists of two buttons, on first button I invoke dailog fragment. using viewModelScope.launch in to fetch details and update UI my dialog fragment .
    viewModelScope.launch
     works perfectly fine when hit for the first time on button click, but does not work for the second time [means when i close my dialog fragment and click back the same button again ]. can you please suggest me how to resolve this issue ??
    r
    • 2
    • 1
  • r

    Rubin MINE

    11/22/2021, 8:11 PM
    Hi everyone, sorry to disturb but I have been searching for some time now and have not yet found a good place to see the widget catalog of Jetpack compose like the one used for Flutter https://docs.flutter.dev/development/ui/widgets

    https://youtu.be/b_sQ9bMltGU▾

    k
    g
    • 3
    • 5
  • m

    Marko Novakovic

    11/22/2021, 9:44 PM
    inside my
    ViewModel
    init
    block am converting
    SavedInstanceState.getLiveData
    to
    Flow
    using
    asFlow
    but when I do that inside
    init
    block my tests are failing because
    InstantTaskExecutorRule
    seems to not take place before
    init
    block. how to go about this?
    m
    • 2
    • 3
  • s

    Slackbot

    11/23/2021, 7:55 AM
    This message was deleted.
    e
    g
    s
    • 4
    • 3
Powered by Linen
Title
s

Slackbot

11/23/2021, 7:55 AM
This message was deleted.
e

ephemient

11/23/2021, 8:38 AM
rules for this entire slack space: https://kotlinlang.org/community/slackccugl.html
- Please remember this is a Slack team for Kotlin. If you have generic questions that are about a technology (which may or may not be used with Kotlin), maybe it’s better to use another forum, such as StackOverflow.
- Use code blocks. Don’t paste code as plain text. Slack supports Kotlin markup. If the code you are pasting is longer than a few lines, use "Code or text snippet" available from + menu next to message input. Only first few lines will be displayed to all users and people interested in the code can expand your code to look into details.
in this channel's topic:
:kotlinnew: :android-new: Using Kotlin to build Android apps. Avoid :not-kotlin:.
:not-kotlin: questions should go here: 😒tackoverflow:; https://discord.com/invite/D2cNrqX, or http://android-united.community/, or https://androidchat.co/
☝️ 1
g

gildor

11/23/2021, 8:39 AM
@Sololo Please, consider delete/edit your message after checking guidelines sent by ephemient above
s

Sololo

11/23/2021, 10:51 AM
OK
View count: 5