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

    Nikola Milovic

    02/24/2020, 1:41 PM
    How do you test a method that calls another method with Junit5 and mockk? I tried googling but no luck. The SUT has a method that after some logic, calls other method. How can i verify that the method was called without calling it? As I want to keep it a unit test. Can i mock the method somehow?
    r
    • 2
    • 8
  • m

    Michael Friend

    02/24/2020, 3:01 PM
    When creating a LiveData in kotlin is there really any difference between
    LiveData<String>
    and
    LiveData<String?>
    ? Since all the methods in LiveData are nullable the the types in
    observe()
    are both nullable and it doesn’t prevent you from setting either value as null. Is it just as a reminder not to set it null?
    s
    a
    • 3
    • 4
  • i

    iex

    02/24/2020, 4:58 PM
    Is there something like
    PublishSubject
    for live data? I.E. which emits events without storing them?
    p
    • 2
    • 9
  • a

    Andy Gibel

    02/24/2020, 8:07 PM
    Is anyone using trunk-based development at work with success? Coming from a world of GitFlow and it's associated problems, I like the idea of constant issue-granular merges behind feature flags but having trouble finding someone who is using this in practice.
    c
    w
    +4
    • 7
    • 25
  • a

    Andrew Ambia

    02/25/2020, 5:54 AM
    Greetings guys, I'm having a challenge, I have a number 15, and need to get an array of integers out of it, where, the last index in that array should be a 1, first index should be a square of a number, and the numbers in between the first and the last index can either be a square and a 1 or a number and 1 example 15 = {3^2, 2^2, 1, 1}; 8 = {2^2, 2, 1, 1}
    👎 1
    n
    r
    s
    • 4
    • 5
  • n

    Nikola Milovic

    02/25/2020, 11:16 AM
    What libraries do you guys use for testing modern Kotlin apps? I tried using Junit5 and MockK, while junit5 seems rather okay, the MockK seems horrible, outdated. EDIT: Use 1.9.3 version of MockK and it works fine
    a
    a
    w
    • 4
    • 4
  • o

    Ofir Bar

    02/25/2020, 12:38 PM
    Hey guys, is it possible to reference the value passed to a
    when
    expression using something similar to
    it
    ? In the code below “`it`” gets an error (
    Unresolved reference: it
    )
    when(mCurrentUserType){
    
    UserType.HUMAN -> {
    setViewForUserType(currentUser, it)
    }
    
    UserType.ANIMAL -> {
    setViewForUserType(currentUser, it)
    }
    
    }
    ❎ 2
    d
    c
    n
    • 4
    • 13
  • b

    bhatnagarm

    02/25/2020, 2:13 PM
    Hey Guys, is it possible in kotlin to limit the scope of a MutableLiveData<String> to some @StringDef
    ❎ 3
    m
    • 2
    • 2
  • s

    stantronic

    02/25/2020, 3:02 PM
    Hallo. Curious about how many people use any form of kotlin reflection in Android apps? Cant find any resources on how much this is encouraged / discouraged.
    w
    a
    +2
    • 5
    • 7
  • k

    Ky

    02/25/2020, 7:43 PM
    Hallo alle. Maybe you can help me with something. I’m currently writing a custom lint rule for my ViewModel classes which checks to make sure no public functions return any type. It’s almost working working except for the fact that my ViewModel’s are
    data class
    and lint seems to be considering the parameters of the
    data class
    as a method.
    data class ListViewModel(
        private val handle: SavedStateHandle,
        private val repository: ListRepository,
        private val scheduler: IObservableSchedulerRx2,
        private val errorHandler: Mvvm.ErrorHandler
    )
    So for each method, I am logging the method name and return type, and this is the output when it hits these params
    METHOD NAME: component1
    FUN RETURN TYPE: PsiType:SavedStateHandle
    component2, component3, etc.. for each subsequent parameter. Any suggestions?
    w
    • 2
    • 7
  • t

    tjohnn

    02/25/2020, 10:05 PM
    What is the general opinion on using kotlinx.serialization on android in terms of size and methods count? Gson just does not do well with kotlin nullability.
    g
    j
    c
    • 4
    • 8
  • e

    eason

    02/27/2020, 2:56 AM
    Hi, im happy with viewBinding feature, but i got one question, i recently using layouts folder to separate layout files, but viewBinding only recognize original “layout” folder path, is there any way i can make viewbing to recognize the path that i create for layouts?
    r
    • 2
    • 2
  • j

    Jason

    02/27/2020, 4:14 AM
    https://developer.android.com/studio/releases/gradle-plugin.html#updating-gradle
    h
    • 2
    • 7
  • b

    bhatnagarm

    02/27/2020, 11:34 AM
    What is the general opinion of Using coroutines inside ViewModel. As blogged by @Sean McQuillan [G] in his blog https://medium.com/androiddevelopers/coroutines-on-android-part-ii-getting-started-3bff117176dd ViewModelScope automatically cancels any coroutine started inside ViewModel after onCleared is called
    z
    • 2
    • 27
  • m

    Muhammad Usman

    02/28/2020, 5:42 AM
    private val registerViewModel by viewModels<RegisterViewModel> (userDao)
    how can i pass object instance to viewModel using by viewModels extentions , like i want to pass userDao to RegisterVIewModel
    s
    • 2
    • 1
  • o

    Ofir Bar

    02/28/2020, 1:47 PM
    Hey guys, for the sake of studying, I am digging inside the code of the abstract class
    LiveData
    . I wonder, why can’t I call
    postValue
    or
    setValue
    If I subclass a LiveData?
    private val someInstanceOfLiveData = object : LiveData<String>(){}
    
    fun test(){
        someInstanceOfLiveData.setValue() // Cannot access 'setValue': it is protected/*protected and package*/ in '<no name provided>'
        someInstanceOfLiveData.postValue() // Cannot access 'postValue': it is protected/*protected and package*/ in '<no name provided>'
    }
    from my understanding,
    object : LiveData<String>(){}
    is a subclass of the abstract
    LiveData
    class. If it is a subclass, why can’t I call
    postValue()/setValue()
    , which are declared as
    protected
    inside the
    LiveData
    ?
    s
    a
    • 3
    • 8
  • i

    iex

    02/28/2020, 4:57 PM
    How to deal with
    activity
    being optional in
    onCreateDialog
    ?
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
        DatePickerDialog(activity!!, this, initDate.year, initDate.month, initDate.day)
    k
    • 2
    • 2
  • s

    Steve

    02/28/2020, 6:33 PM
    I'm writing tests for a feature where people can either scan a code or type it in. Either way, the code goes to a backend for validation. I'm writing tests to validate that, for a given code, the screen does the expected thing. Should I write the same tests using both ways, or would just once be sufficient?
    n
    • 2
    • 2
  • u

    ubu

    02/29/2020, 4:32 PM
    Hi guys, in your opinion, what would be the best way to download files on Android in 2020?
    Ktor
    client,
    Retrofit
    or
    DownloadManager
    API? Or maybe something else.
    d
    a
    +3
    • 6
    • 5
  • s

    Saiteja

    03/01/2020, 10:15 AM
    Whirlpool is looking for Android and iOS developers with 3+ years of experience for Pune location. Interested candidates can share their profiles on saiteja_bogade@whirlpool.com
    🤦‍♂️🏾 1
    :no_red: 3
    p
    • 2
    • 1
  • d

    dave08

    03/01/2020, 5:53 PM
    How do you test Android ViewModels that use a viewModelScope to launch a coroutine and post a result to LiveData...? Even with `
    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()
    and
    shadowOf(Looper.getMainLooper()).idle()
    when I try
    someLiveData.asFlow().first()
    it just stays stuck with runBlocking and crashes with runBlockingTest...
    a
    a
    +2
    • 5
    • 13
  • s

    spencer

    03/02/2020, 4:20 PM
    Is there a trick to using View Binding with multiple modules? The bindings aren’t being generated when I add it to a second module.
    w
    m
    m
    • 4
    • 9
  • a

    Antoine Gagnon

    03/02/2020, 7:44 PM
    Hey, might be a dumb question but I can’t seem to figure out what to use, I have a function making a network call that will return an element that you can wait on to retrieve the response and that can be consumed by multiple listeners. For now I have a Flow but this seems overkill for a single return value.
    m
    f
    • 3
    • 8
  • i

    iex

    03/02/2020, 8:26 PM
    Hi! Can anyone recommend a good permissions library? https://github.com/QuickPermissions/QuickPermissions-Kotlin perhaps?
    l
    t
    • 3
    • 17
  • o

    Omar Ahmed

    03/03/2020, 9:50 AM
    Hi, I built a small library for Android, it helps you to add custom annotations on retrofit calls and retrieve them later via interceptor Check it out and give me your feedback https://t.co/FF72E0GR1s
    👀 1
    🙂 1
    👍 1
    t
    • 2
    • 10
  • b

    Bruno_

    03/03/2020, 6:55 PM
    I couldn't find anything in the docs, I'm familiar with the concept of back stack https://developer.android.com/guide/components/activities/tasks-and-back-stack (in context of AndroidX navigation) let's say that fragment A is my main one (startDestination) and I go to frag B and then to frag C, meaning the stack looks like this A -> B -> C and then if I navigate from C to A, will it look like A -> B -> C -> A or just
    A
    ? There's no back button on the nav bar when I do so so I assume it's the latter but I just want to make sure that it won't cause any problems in the future
    a
    • 2
    • 15
  • o

    Ofir Bar

    03/04/2020, 12:50 PM
    Hey guys, I have a data class
    Advertisement
    which contains a few enums.
    @Parcelize
    data class Advertisement(
        @SerializedName("type") val type : AdvertisementType,
        @SerializedName("userTypeTarget") val userTypeTarget : UserTypeTarget,
        @SerializedName("goal") val advertisementGoal : AdvertisementGoal,
        @SerializedName("attachTo") val attachTo : AttachTo,
    ) : Parcelable
    
    enum class AdvertisementType(private val value : Int) {
        REGULAR(0),
        SOS(1)
    }
    
    enum class AttachTo(private val value : Int){
        ME(0),
        MY_OFFICE(1)
    }
    
    enum class UserTypeTarget(private val value : Int){
        LAWYER(0),
        SERVICE_PROVIDER(1)
    }
    
    enum class AdvertisementGoal(private val value : Int){
        COLLABORATION(0),
        CASE_TRANSFER(1),
        COURT_TRANSFER(2),
        FORM_VALIDATION(3)
    }
    As you can see, my object properties are enums. However, our backend only accepts Integers. I need to make all the properties into Integers, but I don’t want any future developer to ever create an instance of`Advertisement` directly with some Int, and use the created enums instead. How can I force the insertion of enums yet the actual value of created `Advertisement`to be an Int?
    s
    • 2
    • 4
  • a

    Almas Shagdarov

    03/04/2020, 5:32 PM
    Hi everyOne. Does kotlin support java 5(version 49)?
    z
    • 2
    • 3
  • l

    Larten

    03/05/2020, 10:44 AM
    Hi! View binding: If you have a custom view (class TodayBoxView: RelativeLayout) with inflated layout (R.layout.view_todaybox), where must to do ‘binding = ViewTodayboxBinding.bind(this)’ and where binding = null?
    TodayBoxView
    b
    • 2
    • 4
  • a

    Adnan Ali

    03/05/2020, 11:28 AM
    Hi all. What will be the kotlin collection function to convert nested list into hashmap.
    data class Products(id){
    	packList=ArrayList<Packs>
    }
    
    data class Pack(title: string, is_original: Boolean)
    
    val list= productList.map { it.id  to  it.packlist.map{ if (it.is_original==true} it.title}
    Note: ArrayList<Products> But Products= Arraylist<Pack> i.e I want a hashmap just like this ["1" , "[item1, item2, item3, item4]" ]
    d
    f
    z
    • 4
    • 11
Powered by Linen
Title
a

Adnan Ali

03/05/2020, 11:28 AM
Hi all. What will be the kotlin collection function to convert nested list into hashmap.
data class Products(id){
	packList=ArrayList<Packs>
}

data class Pack(title: string, is_original: Boolean)

val list= productList.map { it.id  to  it.packlist.map{ if (it.is_original==true} it.title}
Note: ArrayList<Products> But Products= Arraylist<Pack> i.e I want a hashmap just like this ["1" , "[item1, item2, item3, item4]" ]
d

Dominaezzz

03/05/2020, 12:37 PM
Can you outline the output type you're expecting?
Map<String, String>
?
a

Adnan Ali

03/05/2020, 12:38 PM
Map<String, List<String>>
d

Dominaezzz

03/05/2020, 12:39 PM
I believe you're looking for
associate
.
Just change you outer
map
with
associate
.
a

Adnan Ali

03/05/2020, 12:42 PM
Let me try
associate
if (it.is_original==true) it.title
But this if check is still bypassing, I just want to return list of those pack which have flag
is_original= true
d

Dominaezzz

03/05/2020, 12:50 PM
Use filter.
f

FranSoto

03/05/2020, 1:05 PM
it's a gold rule: First filtering then mapping
a

Adnan Ali

03/05/2020, 1:07 PM
How do I filter first, because nested list is only accessible from outerList index i.e Products List ?
z

Zach Klippenstein (he/him) [MOD]

03/05/2020, 2:48 PM
You can use
mapNotNull
to do a filter + map at the same time:
productList.associate { (id, packlist) ->
  id to packlist.mapNotNull { (title, isOriginal) ->
    title.takeIf { isOriginal }
  }
}
👍 3
a

Adnan Ali

03/06/2020, 6:15 AM
Thanks @Zach Klippenstein (he/him) [MOD]
View count: 1