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
stackoverflow
  • u

    user

    07/13/2022, 6:31 PM
    Is There a Best Way to Chunk a String from the last element to first Is there a good or best way to add some leading zeros for the string chunk that don't have an appropriate number of digits. At the code below I want to split a string where each chunk is composed of 4 digits. To add some leading zeros to a string I use this approach: val text = "1010111".reversed() // 1110101 | len: 7 .chunked(4) { // [1110, 101 *this element only gets 3 digits] val sb = StringBuilder(it) val rem = it.length % 4 /* [1110, 1010 -> now this element have a same...
  • u

    user

    07/13/2022, 6:51 PM
    Fragment Observing ViewModel Property fails on reentering the Activity I have an activity with a fragment that observes the Activity's viewmodel. Everything works fine the first time. When the activity is destroyed, if the user comes back to the Activity, when the activity posts a value to the viewmodel, the fragment observer is never notified. Again, it works the first time and as long as I never destroy the Activity. What am I doing wrong? ACTIVITY private lateinit var viewModel: TowPayViewModel override fun onCreate(savedInstanceState: Bundle?) {...
  • u

    user

    07/13/2022, 7:51 PM
    How to add multiple events in one button Kotlin? I want to pick and upload image from gallery with one button in the same time for Firebase. But the first when i clicked the button it picked up image and the second time when i clicked it uploads. How can i fix it that when i clicked it should be go to gallery and save to Firebase Storage idgir.setOnLongClickListener { if (ContextCompat.checkSelfPermission( this, Manifest.permission.READ_EXTERNAL_STORAGE )...
  • u

    user

    07/13/2022, 7:51 PM
    java.lang.NullPointerException at com.Awwray.awwray.MessageChatActivity$onCreate$2.onDataChange error is on line 73

    this is the error i keep getting when i click on a user▾

  • u

    user

    07/13/2022, 8:51 PM
    How to make between activities animation like a books My question is the same as the title. So how can I do? I have uploaded a video for you to watch. Please help me. Thank you :) Video: CLICK HERE
  • u

    user

    07/13/2022, 8:51 PM
    Best kotlin Guide What’s the best tutorial guide to follow online to start coding in kotlin from scratch
  • u

    user

    07/13/2022, 8:51 PM
    How to show pop up on icon long-click in Jetpack Compose Within the Settings app of Android a handy popup appears whenever I long-click on the vertical dots on the top-right corner of the screen. Can this useful feature be launched using Jetpack Compose? Nothing happens when the code below is used.

    https://i.stack.imgur.com/NEPFv.png▾

    @Composable fun IconMoreVert() { var showMenu by remember { mutableStateOf(false) } IconButton(onClick = { showMenu = !showMenu }) { Icon(...
  • u

    user

    07/13/2022, 8:51 PM
    Using of map or Max by in kotlin I am solving a leet code problem. I found one question in leetcode, which are below You are given an m x n integer grid accounts where accounts[i][j] is the amount of money the i​​​​​​​​​​​th​​​​ customer has in the j​​​​​​​​​​​th​​​​ bank. Return the wealth that the richest customer has. A customer's wealth is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum wealth. Example 1: Input: accounts = [[1,5],[7,3],[3,5]] Output: 10...
  • u

    user

    07/13/2022, 9:11 PM
    Kotlin JSON deserialization with nested class discriminator I want to use a class discriminator in Kotlin to get polymorphic deserialization of JSON messages. The problem is that the class discriminator in my messages is nested one level deep: { "header": { "message_type": "FooBar" } "data": {...} } The contents of data depend on message_type. If message_type were one level higher, this would...
  • u

    user

    07/13/2022, 9:31 PM
    Is it safe update to latest kotlin version while using Compose in a project? I have read about some people having compiler problems when they update to the latest version of Kotlin while using Jetpack Compose in a project. I currently learning Compose and Android Studio is offerring me to update to Kotlin 1.7.0, but I´m not sure that if I do, it will still working. I'm using AS Chipmunk and a regular Compose project (not the material 3 one).
  • u

    user

    07/13/2022, 10:11 PM
    Dagger2. How to use multibinding with supporting of assisted injection? I have an interface PaymentProvider: interface PaymentProvider { fun pay(amount: Double): Boolean } Here is different implementations: class PayPalPayment @AssistedInject constructor( private val payPalRepo: PayPalRepository, @Assisted private val paymentData: PaymentData ): PaymentProvider { @AssistedFactory interface Factory : PaymentProviderFactory override fun pay(amount: Double): Boolean { // some code } } class CreditCardPayment( private...
  • u

    user

    07/13/2022, 10:31 PM
    How to fix **error: cannot find symbol** when importing kotlin package into MainApplication.java for Android in React Native app? I'm building a react native app that uses the react-native-vision-camera by Mrousavy (https://github.com/mrousavy/react-native-vision-camera) and I'm trying to create a frame processor plugin, following this guide <a href="https://mrousavy.com/react-native-vision-camera/docs/guides/frame-processors-plugins-android" rel="nofollow...
  • u

    user

    07/13/2022, 11:51 PM
    Touch to focus not getting the accurate focus area I am using Camera2 API for my app to communicate to camera device of android device, Then I'm trying to make a touch to focus feature unfortunately the focus area is not accurate. I was tried different work around and suggestions in google but I can't get the right focus area when I touch the screen. Is there anyone here make this feature working smoothly using kotlin? here's the snippet of my code the calculate the focus area val sensorArraySize: Rect? =...
  • u

    user

    07/13/2022, 11:51 PM
    What is the simple way to add a left icon to each line, in an alert list dialog using Kotlin? In my Android (write in kotlin) App I have an alert dialog with a similar structure like this. The list of items is injected from a json, but for this question I made the code more simple.
    var items = mutableListOf()
    items.addAll(listOf("line 1", "line 2", "line 3", "line x"))
    val builder = android.app.AlertDialog.Builder(this@aplicacion)
    var items2=items.toTypedArray()
    with(builder)
    {
    setItems(items2) { dialog, i ->
    var...
  • u

    user

    07/14/2022, 12:51 AM
    For accessing data from api ,by retrofit. in android ,not able to link with service class apiInterfac which i have created TO access api by Retrofit , Retrofit builder object i am able to use retrofitbuilder object , connect url , build butnot able to attach my service class apiInterface which i have created . private fun getmydata() { lateinit var myAdapter: RecyclerAdapter val retrofitBuilder = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .baseUrl(myuri) .build(); var api : apiInterface =...
  • u

    user

    07/14/2022, 2:31 AM
    Change an image of a called composable in Jetpack compose A question, maybe a little basic since I am in an early learning phase. If I want to change the image of a composable when calling it, how would I do it? I know that this is possible with Int and Strings thanks to the parameters that I define in the original function, but how would it be done in the case of images? @Composable fun ComposableTest(exampleText:String){ Column() { Image ( painter = painterResource(R.drawable.sample_image), contentDescription...
  • u

    user

    07/14/2022, 3:11 AM
    Fragment inflate not intended xml file I have a problem that EditSleepPressureFactorFragment inflates other xml file fragment_sleep_record.xml. But my intention is to inflate fragment_edit_sleep_pressure.xml. A Spinner having an id "year_spinner" is in fragment_edit_sleep_pressure.xml but binding!!.yearSpinner code occure unsolved refference. And binding!!.startSleepYear code cause no error. "start_sleep_year" id is in fragment_sleep_record.xml. How I solve this problem? EditSleepPressureFragment.kt import android.os.Bundle...
  • u

    user

    07/14/2022, 3:31 AM
    Android custom view attributes not being applied to view I am working on a paint app, and I have created a custom view called ColorSwitcherView which holds the primary/secondary color state: package com.therealbluepandabear.pixapencil.customviews.colorswitcherview import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.MotionEvent import android.view.View import androidx.core.content.ContextCompat import com.therealbluepandabear.pixapencil.R class...
  • u

    user

    07/14/2022, 3:51 AM
    How can I call object/function inside an if-else statement in Kotlin I have a library that assigned me to integrate it GuardianSdk.getInstance().hasDuplicateUserKey(userName(), object : GuardianResponseCallback { override fun onSuccess(result: ResultResponse) { Log.i(TAG, "Result code : " + result.rtCode) } override fun onFailed(errorResult: ErrorResult) { Log.e(TAG, "Error code : " + errorResult.errorCode) } }) I...
  • u

    user

    07/14/2022, 4:11 AM
    androidx.Biometrics library - setOnCancelListener for cancellation signal not working, onAuthenticationError being called randomly Here's what I'm experiencing - I call the biometrics function as soon as the app launches. So, as soon as the prompt is displayed, the onAuthenticationError gets called. Don't know why, but seems useful in solving the issue. The listener in cancellationSignal doesn't get called when I press the prompt's cancel button. touching outside the prompt dismisses the prompt. But, not without calling the onAuthenticationError function again. The device I am using is a Huawei nova 3 with android 9.0. I...
  • u

    user

    07/14/2022, 4:11 AM
    Classes, Initializer block and Constructor in Kotlin I am a newbie to kotlin and I'm struggle to understand the relationship between initializer block, primary constructor and secondary constructor. I saw some video on youtube discussing about them but I am still confuse. Is the body in the class same as the body of constructor and what are the sequence for them to execute? What are the differences between the primary constructor and secondary constructor. Furthermore, how is the this works?
  • u

    user

    07/14/2022, 4:11 AM
    How will usage of kapt(Kotlin Annotation Processing Tool) while kapt being in maintenance mode alters my project? I think kapt will not work when I use it in my project while it is in maintenance mode. Because when I use it in my project it throws me this error :app:kaptDebugKotlin task failed. :app:kaptReleaseKotlin task failed. , and I think there is nothing wrong in my codes and I have tried different ways and I am pretty sure that this error due to kapt because error only occurs when I use kapt in my project.

    https://i.stack.imgur.com/W4geY.png▾

  • u

    user

    07/14/2022, 5:11 AM
    How can I add an animation to an item when it is selected in a LazyRow or Column in Jetpack Conpose? I am trying to make it so that the item in a LazyRow clips to the center of the screen, and if it is in the center is becomes larger while the items next to it return to the original size. Below is an example

    https://i.stack.imgur.com/IQh6i.gif▾

  • u

    user

    07/14/2022, 5:31 AM
    kotlin arrayadapter Error none of the following functions can be called with the arguments supplied I have a ListView and I am trying to use an array to fill in the list view. But I am getting the following error: None of the following functions can be called with the arguments supplied. I have tried some alternatives, but they didn't work. Does someone have any suggestions? This is my code import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import androidx.fragment.app.Fragment import...
  • u

    user

    07/14/2022, 6:31 AM
    Android - Detecting when a view's constraints have been fully resolved/loaded I have quite a complex problem to do with Android views, I am creating a paint application, and I have two views: a transparent background view and the pixel art board. For both views, I want the height and width to be calculated off of the distance between view A and B:

    https://i.stack.imgur.com/stkM9.png▾

    Instead of calculating the distance between these two views, I simply 'constraint' a view in the middle like so, and then extract its height by...
  • u

    user

    07/14/2022, 6:31 AM
    How can I start dynamic rendering on canvas and stop or change the rendering when the onTouchEvent event occurs? There is a separate View class that implements rendering on canvas and listening for onTouchEvent events. How can they be run in different coroutines or threads, but so that events can stop or change rendering? class CustomView( context: Context, attributesSet: AttributeSet? ) : View(context, attributesSet) { ... private val pointer=... var x = false override fun onDraw(canvas: Canvas) { super.onDraw(canvas) while(true){...
  • u

    user

    07/14/2022, 6:51 AM
    The problem of saving data in the database and closing the program quickly after execution I have a layout that has two EDITETEXT and they should be filled and saved in the database by pressing the save button Everything is correct, but when I write the button code, the program runs and quickly exits the program (And that there is no mistake) If I want to say complete, it means: everything is correct until I want to use the database :| code main activity: enter codeclass MainActivity : AppCompatActivity() { private lateinit var adapter: Adapter private lateinit var...
  • u

    user

    07/14/2022, 7:31 AM
    How can I create widget with timer? I am working on one application with has a widget functionality So I have designed a widget but tried with timer. widget is working on background after kill the app.so can you guide me to set current time on my widget.
  • u

    user

    07/14/2022, 7:31 AM
    Creating recyclerview with variable height of item as per the content text with swipeable feature How to create a recyclerview with items having variable height as per the length of content text like the below image. Recyclerview also supports swipeable items. Expected

    https://i.stack.imgur.com/EEb4N.png▾

    Actual

    https://i.stack.imgur.com/eUONS.png▾

    My layout...
  • u

    user

    07/14/2022, 8:11 AM
    passing array to functional interface but get (Array&lt;out TypeVariable(T)&gt;) -&gt; Array&lt;out TypeVariable(T)&gt;? type mismatch val changeFirstElement = VarargsFunction { ss: Array -> ss[0] = ss[0]!! + " world" ss } val params = arrayOf("hello") } fun interface VarargsFunction { fun apply(vararg t: T): Array? } I get this following exception: Type mismatch: inferred type is (Array) -> Array? but (Array) -> Array? was expected Any suggestion why is this exception and how to resolve it? Thanks Playground link https://pl.kotl.in/kBwQZlCZj
Powered by Linen
Title
u

user

07/14/2022, 8:11 AM
passing array to functional interface but get (Array&lt;out TypeVariable(T)&gt;) -&gt; Array&lt;out TypeVariable(T)&gt;? type mismatch val changeFirstElement = VarargsFunction { ss: Array -> ss[0] = ss[0]!! + " world" ss } val params = arrayOf("hello") } fun interface VarargsFunction { fun apply(vararg t: T): Array? } I get this following exception: Type mismatch: inferred type is (Array) -> Array? but (Array) -> Array? was expected Any suggestion why is this exception and how to resolve it? Thanks Playground link https://pl.kotl.in/kBwQZlCZj
View count: 3