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

    Vivek Modi

    07/18/2022, 12:08 PM
    Hey guys can somone tell me what is the use of
    private set
    in here ?
    var number : Int by mutableStateOf(0)
            private set
    k
    h
    • 3
    • 4
  • l

    loloof64

    07/19/2022, 3:44 PM
    Hi everyone. In my android project, I set up minimal API to 21. But I can't use kotlin function String#chars() in order to transform a String to an array of chars. So I wonder if I can find the implementation of the extension function somewhere or if there is a simple way to do it ?
    e
    • 2
    • 3
  • a

    Ali Khaleqi Yekta

    07/19/2022, 6:36 PM
    Hi There's a syncing problem that literally stopped me for a month from upgrading the AGP _(which will most likely fix an IDE false positive error about resolving common dependencies in
    androidMain
    )_; I'd be really happy to even get a clue of what to touch to make this work. I tried countless ways but nothing worked: https://stackoverflow.com/questions/73006307/gradle-sync-cannot-find-a-variant-matching-build-type-null-and-product-flavo
    s
    l
    • 3
    • 5
  • m

    Mobile Dev.

    07/20/2022, 9:36 PM
    Hi folks, i'm trying to use window manager only in app activites. I dont want to get permission from user for this. Some of API devices it works without crash. In my device i'm starting the window manager service and putting a small view to screen and its staying all of activities as i wanted. When i throw the app to the background it's not showing and i want this so it's okay. But some of API for example 11.0 it throws an error for permission. Whatsapp doesn't even ask permission for video call. I dont know is it true way to do this but simply i have to create a view which can be draggable and must be appear all of activities in the app. and here is my code line
    windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
    
    val inflater = baseContext.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater
    
    floatView = inflater.inflate(R.layout.floating_layout, null) as ViewGroup
    
    webView = floatView.findViewById(R.id.webView)!!
    
    LAYOUT_TYPE = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
    } else {
        WindowManager.LayoutParams.TYPE_TOAST
    }
    
    floatWindowLayoutParams = WindowManager.LayoutParams(
        150.toPx(baseContext),
        200.toPx(baseContext),
        LAYOUT_TYPE!!,
        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
        PixelFormat.TRANSLUCENT
    )
    
    floatWindowLayoutParams.gravity = Gravity.CENTER
    floatWindowLayoutParams.x = 0
    floatWindowLayoutParams.y = 0
    
    windowManager.addView(floatView, floatWindowLayoutParams)
    and when i want to start the view
    btnWebView.setOnClickListener {
        startService(Intent(this, FloatingWindowApp::class.java))
    }
    Can you help me ?
    :kotlin-intensifies: 2
    :not-kotlin: 3
  • v

    Vivek Modi

    07/21/2022, 7:58 PM
    Hey guys what this error means?
    Serializer has not been found for type 'ZonedDateTime'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
    @Serializable
    @Parcelize
    data class NearestResult(
        val day: ZonedDateTime,
        val event: String
    ) : Parcelable
    l
    p
    • 3
    • 4
  • d

    Derek Alves

    07/22/2022, 6:25 PM
    hey guys, have a channel for jetpack compose?
    s
    • 2
    • 1
  • p

    Prayansh Srivastava

    07/22/2022, 7:03 PM
    hi all 👋 ! When yall are creating a new library what is the minSdk version that you tend to target? Its not a UI library, but more of a utility lib, if that helps
    :not-kotlin: 1
  • s

    spierce7

    07/22/2022, 8:55 PM
    I’m trying out Android ViewModels for the first time. It seems like the general practice is to have a
    Flow
    to watch the data changes from within the ViewModels, and then functions to pass events into the ViewModels, and to start loading etc. How should errors be handled when a network request fails? Should it be part of the observed Flow type, or is there a better way to handle this?
    f
    • 2
    • 1
  • j

    Jasmin Fajkic

    07/23/2022, 6:39 PM
    I am quite new with android and have issue that I do not know how to solve. I use Assisted injection with dagger hilt and I have ViewModelFactoryProvider that looks like this
    @EntryPoint
    @InstallIn(ActivityComponent::class)
    interface ViewModelFactoryProvider {
        fun communityFeedViewModelFactory(): CommunityFeedViewModel.Factory
        fun postTileViewModelFactory(): PostTileViewModel.Factory
        fun reactionViewModelFactory(): ReactionsViewModel.Factory
        fun commentViewModelFactory(): CommentViewModel.Factory
    }
    Here is for example how i use it in ReactionsViewModel
    class ReactionsViewModel
    @AssistedInject
    constructor(
        @Assisted private var reactions: PostReactions,
        @Assisted private var postId: String,
        private var reactionsRepository: ReactionsRepository,
    ) : ViewModel() {
    
        @AssistedFactory
        interface Factory {
            fun create(
                @Assisted reactions: PostReactions,
                @Assisted postId: String,
            ): ReactionsViewModel
        }
    
        @Suppress("UNCHECKED_CAST")
        companion object {
            fun provideFactory(
                assistedFactory: Factory,
                reactions: PostReactions,
                postId: String
            ): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
                override fun <T : ViewModel> create(modelClass: Class<T>): T {
                    return assistedFactory.create(reactions, postId) as T
                }
            }
        }
    }
    
    @Composable
    fun reactionsViewModel(
        reactions: PostReactions,
        id: String
    ): ReactionsViewModel {
        val factory = EntryPointAccessors.fromActivity(
            LocalContext.current as Activity,
            ViewModelFactoryProvider::class.java
        ).reactionViewModelFactory()
        return viewModel(
            factory = ReactionsViewModel.provideFactory(
                factory,
                reactions,
                postId = id,
            ), key = id
        )
    }
    And here is how I provide reactions respository:
    @Module
    @InstallIn(ActivityComponent::class)
    object ReactionsModule {
        @Provides
        fun provideReactionApi(retrofit: Retrofit):
                ReactionsApi = retrofit.create(ReactionsApi::class.java)
    
        @Provides
        fun providesRRepository(ReactionsApi: ReactionsApi):
                ReactionsRepository =
            ReactionsRepositoryImpl(ReactionsApi)
    }
    Problem here is that I need to use ActivityComponent in module where I provide repository. If i try to access this reactions repository in any other viewmodel it crash because it needs to be ViewModelComponent. Is there any clever solution how to fix it?
    :not-kotlin: 1
    :thread-please: 1
  • l

    loloof64

    07/23/2022, 7:56 PM
    Hi ! I'm writing an android C++ plugin. But I am getting the following lines in the terminal. Are they a sign of a bad behaviour from the native side ?
    I/System.out: referenceTable GDEF length=778 1
    I/System.out: referenceTable GSUB length=6388 1
    I/System.out: referenceTable GPOS length=66796 1
    I/System.out: referenceTable head length=54 1
    👍 1
    :not-kotlin: 3
  • a

    Asad Mukhtar

    07/23/2022, 7:56 PM
    Hi everyone is there anyone who use accompanist pager library in production ? I`m facing issues when user scroll to next page it takes few milliseconds to compose the ui and in that milliseconds old page ui is shown that`s so weird behaviour?
    l
    • 2
    • 2
  • g

    galex

    07/24/2022, 3:23 PM
    Sorry for being offtopic, but I've got a question about
    okhttp
    and I didn't find a better place to ask this 😊 We're using
    okhttp
    with
    Retrofit
    and
    Apollo
    , and I'd like to get the full http request right before it is really being executed. I can get the
    Call.request()
    to get the request object but this one doesn't contain the headers we're adding through interceptors for example... Is there any extension to get the real request? Or am I correct to assume I can't use interceptors if I want to achieve this?
    :stackoverflow: 1
    c
    • 2
    • 2
  • k

    Kareem Waleed

    07/25/2022, 6:48 AM
    Hi! I’m developing an Android library that would be a container for some common code to be used. The problem is, I’m not able to use the extension functions defined in the library by a consumer app. The library is of course published and obfuscated, so I’ve tried to keep the file holding these top-level extensions in
    proguard
    -keep public class com.example.library.ExtensionsKt{*;}
    but this only made using the function
    ExtensionsKt.doSomething()
    possible but not
    Model.doSomething()
    Any ideas ?
  • y

    yousef shaaban

    07/25/2022, 9:28 AM
    Hi any idea about this error when upgrade kotlin version from 1.6.20 to 1.7.10 and upgrade Android Gradle plugin AGP to 7.2.0 then run task call detektDebug task at the gradle i used detekt version 1.19.0 then i faced this error when run task incompatible classes were found in dependencies. Remove them from the classpath or use ‘-Xskip-metadata-version-check’ to suppress errors
    c
    • 2
    • 1
  • a

    Artem Bezlyubchenko

    07/25/2022, 1:58 PM
    Hello. I’m using kotlinx.serialization with
    explicitNulls = false
    , but I have 1 request, where I need to keep nulls… Is there a way to keep nulls for this particular request without creating a separate client for this? Thanks!
    s
    • 2
    • 1
  • g

    Gaurav

    07/25/2022, 4:06 PM
    Hello, i have overridden onBackPressed()...
    override fun onBackPressed() {
             if (supportFragmentManager.backStackEntryCount <= 1) {
                 finish()
             } else {
                 supportFragmentManager.popBackStack()
             }
         }
    now sometime i am getting this exception
    java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
    this may be happening bcoz state is getting saved and then popBackStack() is called... need help...how to handle this situation...i can put a check isStateSaved or not....but i want to handle those cases also where state is saved and user clicked on back press....What to do in such scenario...How to do back press handling when state is saved?? please suggest some solution.. Thanks a lot in advance.:thank-you:
    n
    r
    • 3
    • 5
  • t

    Tarun Deep Attri

    07/26/2022, 8:42 PM
    hey I am opening camera from a site say abc.com on android smartphone on chrome. But when I use same abc.com and load it in a webview, pressing same button does not open camera. I have given Camera Permission in Manifest. Can someone suggest why it might be happening?my use case is to open camera from a web app say abc.com which is being displayed in webview of my app without using javascript interface. On this forum should only kotlin related questions should be there? Should I delete this question? can sombody pls dm me this?
  • s

    Shashi K

    07/27/2022, 2:54 AM
    Hello Team, Would like to know from team is there a Kotlin based Routing (Screen Navigation) library is available, like ARoute
  • m

    Manuel Lorenzo

    07/27/2022, 9:40 AM
    hi everybody! I have an activity that observes a Flow in my VM. The VM is in charge of obtaining the user location, and fetching the nearby places. However, when I rotate the device, I see that the API request being fired again from the VM, and it looks like permission related:
    @AndroidEntryPoint
    class MainActivity : AppCompatActivity() {
        private val placesViewModel: PlacesViewModel by viewModels()
        private val locationPermissionRequest =
            registerForActivityResult(
                ActivityResultContracts.RequestPermission()
            ) { permissionGranted ->
                when {
                    permissionGranted -> placesViewModel.getNearbyPlaces(locationPermissionGiven = permissionGranted)
                    else -> showLocationPermissionDeniedExplanationDialog(permissionGranted)
                }
            }
        // region Activity lifecycle
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.main_activity)
            val adapter = PlacesAdapter()
            val recyclerView = findViewById<RecyclerView>(R.id.placesRecyclerView)
            val loadingProgressIndicator =
                findViewById<CircularProgressIndicator>(R.id.loadingProgressIndicator)
            recyclerView.adapter = adapter
            lifecycleScope.launch {
                observeChanges(loadingProgressIndicator, adapter)
            }
            checkForLocationPermissionsAndHandleResult()
        }
    
        private suspend fun observeChanges(
            loadingProgressIndicator: CircularProgressIndicator,
            adapter: PlacesAdapter
        ) {
            placesViewModel.uiState.collect {
                when {
                    it.loading -> loadingProgressIndicator.visibility = View.VISIBLE
                    it.places?.isNotEmpty() == true -> {
                        loadingProgressIndicator.visibility = View.GONE
                        adapter.submitList(it.places)
                    }
                }
            }
        }
    
        // endregion
    
        // region Location permission related methods
    
        /**
         * Shows a dialog explaining that the [Manifest.permission.ACCESS_FINE_LOCATION] has been denied
         * and that a default location will be used in order to fetch the nearby places.
         */
        private fun showLocationPermissionDeniedExplanationDialog(permissionGranted: Boolean) {
            AlertDialog.Builder(this)
                .setMessage(getString(R.string.permission_denied_dialog_message))
                .setPositiveButton(getString(R.string.permission_denied_dialog_positive_button_text)) { _, _ ->
                    placesViewModel.getNearbyPlaces(locationPermissionGiven = permissionGranted)
                }
                .show()
        }
    
        /**
         * Check for the [Manifest.permission.ACCESS_FINE_LOCATION] permission.
         * If the permission is granted, fetch the user's nearby places with [placesViewModel.getNearbyPlaces()].
         * Otherwise, show a dialog explaining that because of denying the location permission, a default location will be used.
         */
        private fun checkForLocationPermissionsAndHandleResult() {
            when {
                ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.ACCESS_FINE_LOCATION
                ) == PackageManager.PERMISSION_GRANTED -> {
                    placesViewModel.getNearbyPlaces(locationPermissionGiven = true)
                }
                shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION) -> {
                    AlertDialog.Builder(this)
                        .setMessage(getString(R.string.permission_dialog_message_text))
                        .setNegativeButton(getString(R.string.permission_dialog_negative_button_text)) { dialog, _ ->
                            dialog.dismiss()
                            placesViewModel.getNearbyPlaces(locationPermissionGiven = false)
                        }
                        .setPositiveButton(getString(R.string.permission_dialog_positive_button_text)) { dialog, _ ->
                            locationPermissionRequest.launch(Manifest.permission.ACCESS_FINE_LOCATION)
                            dialog.dismiss()
                            placesViewModel.getNearbyPlaces(locationPermissionGiven = true)
                        }.show()
                }
                else -> {
                    locationPermissionRequest.launch(Manifest.permission.ACCESS_FINE_LOCATION)
                }
            }
        }
        // endregion
    }
    • 1
    • 1
  • m

    Manuel Lorenzo

    07/27/2022, 9:41 AM
    am I doing something wrong here? when rotating the device
    locationPermissionRequest
    is generated again, to check for the permissions, so the VM is triggered again
  • o

    oday

    07/27/2022, 1:44 PM
    anyone tried to use the new way of
    startActivityForResult
    ? I have an Activity A that I start a Fragment A-2 inside, and that fragment A-2 starts another activity B, I need activity B to send back the result all the way to activity A using this new registerActivityForResult way
    • 1
    • 1
  • l

    Landry Norris

    07/27/2022, 9:21 PM
    It looks like Qodana says it was designed for server usage. Has any one used the JVM support for Android? Is it a good choice for a quality checker for Android?
    m
    • 2
    • 3
  • a

    althaf

    07/28/2022, 7:07 AM
    Hi there, is there way to shorten this code
    var messageStyle: MessageStyle = MessageStyle.Large
        set(value) {
            var textStyle = 0
            var iconSize = 0
            var padding = 0
    
            when (value) {
                MessageStyle.Small -> {
                    textStyle = R.style.TextAppearance_Sc_Components_Body2_Regular
                    iconSize =  context.resources.getDimensionPixelSize(R.dimen.icon_size_small)
                    padding = R.dimen.sc_space_xs
                }
                else -> {
                    textStyle = R.style.TextAppearance_Sc_Components_Body1_Regular
                    iconSize =  context.resources.getDimensionPixelSize(R.dimen.icon_size_regular)
                    padding = R.dimen.sc_space_xs
                }
            }
            tvMessage.setTextAppearance(textStyle)
            ivMessageVariantIcon.layoutParams = ViewGroup.LayoutParams(iconSize,iconSize);
            setPaddingRelative(padding, padding, padding, padding)
            field = value
        }
    m
    • 2
    • 1
  • c

    Chetan Tuteja

    07/28/2022, 8:38 AM
    Hey guys! Does anyone know if we have a replacement for the
    ems
    property in Jetpack Compose?
    m
    c
    • 3
    • 12
  • k

    KotlinLeaner

    07/28/2022, 8:57 AM
    Hey guys, I am new in kotlin. I want to ask what is the best way of doing declare const val.
    companion object {
       const val TABLE_USER_ATTRIBUTE_EMPID = "_id"
       const val TABLE_USER_ATTRIBUTE_DATA = "data"
    }
    vs
    object DbConstants {
        const val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        const val TABLE_USER_ATTRIBUTE_DATA = "data"
    }
    which is one recommended way ?
    j
    • 2
    • 1
  • j

    juliocbcotta

    07/28/2022, 9:36 AM
    Could anyone try to help me with this ? https://kotlinlang.slack.com/archives/C09222272/p1658483494439749 I couldn't find an issue on android issue tracker or in the jetbrains issue tracker...
    n
    • 2
    • 3
  • h

    Harsh P.

    07/28/2022, 9:16 PM
    Hello, I'm actually trying to implement this but it is not working out. Can anyone help me with this? Thank you. https://stackoverflow.com/questions/54827455/how-to-implement-timer-with-kotlin-coroutines
    l
    • 2
    • 12
  • a

    Asad Mukhtar

    07/29/2022, 12:28 PM
    Hi everyone, i have a separate Module in which i want to inject Activity using Hilt, but from app module if i start the activity app crash and logs are here: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/gallery/Hilt_GalleryActivity; at java.lang.Class.newInstance(Native Method) I try to do rnd not able to find the solution so please anyone help me?
    c
    • 2
    • 1
  • v

    Vivekpanchal64

    07/29/2022, 3:19 PM
    is there any way in Camera x that we get output as compressed.? any resources would be really helpful
  • a

    AmrJyniat

    07/30/2022, 11:11 AM
    Is there a
    findOr
    fun like
    find{}
    in Kotlin collections but let me do another thing if the result was null?
    p
    z
    h
    • 4
    • 9
Powered by Linen
Title
a

AmrJyniat

07/30/2022, 11:11 AM
Is there a
findOr
fun like
find{}
in Kotlin collections but let me do another thing if the result was null?
p

Paul Woitaschek

07/30/2022, 1:13 PM
I don’t think there is as it wouldn’t provide much benefit over doing a ?:
I can’t see where that would be useful
users.findOrElse({ it.name == "Alice" }) {
  Person("alice")
}
a

AmrJyniat

07/30/2022, 1:22 PM
val rightDevice = devices.find { it is AudioDevice.BluetoothHeadset 
} ?: 
devices.find { it is AudioDevice.WiredHeadset 
} ?:
devices.find { it is AudioDevice.Earpiece }
Trying to make this code a bit cleaner
p

Paul Woitaschek

07/30/2022, 1:27 PM
That looks pretty clean to me already
fun <T : Any> List<T>.multiFind(vararg predicates: (T) -> Boolean): T? {
  predicates.forEach { predicate ->
    find(predicate)?.let { return it }
  }
  return null
}
😉
Ah or better: Go with a sorting!
devices.maxByOrNull {
  when(it) {
    is bluetooth -> 3
    is wired -> 2
    is earpiece -> 1
  }
}
z

Zun

07/30/2022, 8:33 PM
What about “devices.any { it in listOfEnums }”
p

Paul Woitaschek

07/31/2022, 8:14 AM
That original algorithm has a prioritization and prefers Bluetooth over wired over earpieces.
h

hfhbd

07/31/2022, 11:18 AM
In theory, you could also iterate only once: return if bluetooth found or store the first wired and the first earpiece. and return wired ?: earpiece 🙂
var wired: Device? = null
var earpiece: Device?  = null
for (device in devices) {
  if (device is Bluetooth) { return device }
  if (device is Wired && wired == null) { wired = device }
  if (device is EarPiece && earpice == null) { earpiece = device }
}
return wired ?: earpiece
Even better with a sealed class and when
View count: 9