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
getting-started
  • d

    Daniele B

    08/13/2020, 9:18 PM
    Given a data class like this:
    data class State (
    	val aField : String
    	val bField : String
    	val cField : String
    )
    I would like to wrap this copy function:
    wrapperobject.state = wrapperobject.state.copy (aField = aValue, bField = bValue)
    inside a custom method like this:
    wrapperobject.changeState(aField = aValue, bField = bValue)
    what would be the code for it? I am not sure how to define the argument of the
    changeState
    method
    s
    • 2
    • 12
  • c

    Colton Idle

    08/14/2020, 5:31 AM
    Is there any reason why something like
    isNotNullOrEmpty
    doesn't exist by default? I hate having to do
    !something.isNullOrEmpty
    t
    l
    n
    • 4
    • 10
  • c

    Colton Idle

    08/14/2020, 6:58 AM
    Both
    when (it) {
        is EventDriver.Stop -> ...
        is EventDriver.Go -> ...
    }
    and
    when (it) {
        EventDriver.Stop -> ...
        EventDriver.Go -> ...
    }
    seem to compile and run fine. What's the difference? I would have expected
    is
    to be required here?
    p
    n
    b
    • 4
    • 9
  • j

    Joshlemer

    08/15/2020, 1:26 PM
    Hey, I’m just wondering if there are any interesting use-cases of suspend functions outside of the two obvious ones: coroutines and generators?
    r
    • 2
    • 1
  • m

    Martin KvL

    08/15/2020, 4:42 PM
    Hello Kotlin Community. I'm looking for a deep dive in Kotlin with Spring Boot. I'm new to Spring and don't have any Java Experience. This is why most ( actually good) Tutorials don't bring me further. Thanks for your help 😘
    t
    • 2
    • 8
  • d

    Daniele B

    08/15/2020, 9:07 PM
    is it possible in kotlin to retrieve a value previously calculated for sorting, so that I don’t have to calculate it twice?
    myList
    .sortedBy { val calculatedField = it.fieldA / it.fieldB }
    .mapIndexed { index, elem -> MyNewObject(
        _index = index+2, 
        _value = calculatedField,
        _fieldA = fieldA.toInt()
        _fieldB= fieldB.toInt()
      )
    }
    unfortunately this code doesn’t work: I can’t access calculatedField from inside the map function
    d
    p
    +2
    • 5
    • 8
  • b

    blue

    08/15/2020, 11:16 PM
    Is
    ==
    and
    equals
    same in Kotlin? If so, can someone help me why my program is returning
    false
    for below inputs
    John 19 0
    John 19 22
    import java.util.*
    
    data class Client(val name: String, val age: Int, val balance: Int) {
        fun equals(other: Client?): Boolean {
            return this.age == other?.age && this.name == other.name
        }
    }
    
    fun main(args: Array<String>) {
        val input = Scanner(System.`in`)
    
        val n = input.next()
        val a = input.nextInt()
        val b = input.nextInt()
    
        val nn = input.next()
        val aa = input.nextInt()
        val bb = input.nextInt()
    
        println(Client(n, a, b) == (Client(nn, aa, bb)))
    }
    z
    n
    m
    • 4
    • 14
  • h

    huehnerlady

    08/17/2020, 11:20 AM
    I would like to write a test method to check whether every field of an object is not null. So if I have a data class
    data class Test(val property1: String?, property2: Int?)
    and I would like to check if that property1 and property2 are not null. But I would like this generic for any object, not this specific one. I currently check, if the String of the object does not contain null, BUT this feels a bit hacky. Any idea how I can do that better?
    m
    j
    • 3
    • 9
  • c

    Colton Idle

    08/17/2020, 7:36 PM
    I have a java method written as such
    static Function1<MyManager, String> doTheManaging(){
        return MyManager::condense;
    }
    The kotlin converter can't seem to convert this. Can anyone point me in the right direction? Converter gives me a new companion object then
    fun doTheManaging(): Function1<MyManager, String> {
     return { valueMap: Map<String, Any> -> condense(valueMap)}
    }
    but the entire return statement is red
    n
    • 2
    • 11
  • m

    Mark

    08/19/2020, 4:59 AM
    After updating to Kotlin 1.4, I get a couple of type inference issues regarding
    emptyList()
    for example:
    val retrievedList = myMap[someKey] ?: emptyList()
    now gives a compiler warning (though the IDE doesn’t complain) when trying to access items in
    retrievedList
    so I need to explicitly set
    List<MyListItemType>
    as the
    retrievedList
    type or the
    emptyList()
    generic. I can’t seem to reproduce this in the kotlin playground, so can only assume there is some inconsistency caused by my gradle build scripts or some build caching issue.
    e
    • 2
    • 1
  • e

    Eugene Freeman

    08/19/2020, 7:09 AM
    Hi guys What article about kotlin coroutines you would recommend must read? I am trying to wrap my head around of how coroutines works in nutshell. Thanks in advance
    f
    d
    m
    • 4
    • 7
  • c

    Carrascado

    08/19/2020, 6:01 PM
    Does anyone know why this happens? I started a fresh gradle project with Kotlin for JVM, it appears all grey
    n
    r
    e
    • 4
    • 6
  • u

    ursus

    08/20/2020, 9:49 PM
    is this the best we can do ?
    pages.toMutableMap().apply { this[currentPage] = it }.toMap())
    n
    i
    • 3
    • 3
  • d

    Divelix

    08/21/2020, 7:03 AM
    Is it possible to split inner classes to separate files somehow?
    t
    • 2
    • 3
  • b

    Ben Butterworth

    08/21/2020, 9:55 PM
    Im sure everyone else knows this, but i havent been able to google/ stackoverflow this: in
    scope.launch{}
    , what do you call those curly braces? I know the last parameter type seems to have to be a lambda, often called
    block
    n
    b
    +2
    • 5
    • 23
  • w

    Will Nixon

    08/23/2020, 11:57 PM
    Is there a way to see if a device is capable of making telephone calls? Either to cell or landline? I know, in theory, someone with Skype installed could make calls through that, but I just want to check the main phone capabilities, and then hide a list of contact buttons should the device not be capable of making calls
    :google: 1
    :stackoverflow: 1
    p
    • 2
    • 2
  • k

    Kevin

    08/24/2020, 6:53 AM
    Hi all, this is probably a newbie question. but i'm curious to know, whether in kotlin you can call components from other file into main file. i've tried to research about this before, but i can't find any resources that explaining about this stuff. here is the example of what i mean: main.xml
    <LinearLayout
       android:id="@+id/linear_main"
       xmlns:android="<http://schemas.android.com/apk/res/android>"
       xmlns:tools="<http://schemas.android.com/tools>"
       xmlns:app="<http://schemas.android.com/apk/res-auto>"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="horizontal"
       >
    
       <TextView
    			android:layout_width="match_parent"
    			android:layout_height="wrap_content"
    			android:text="Hello World"
    			android:textColor="@color/Black01"
    			/>
    
      /*insert some kind of tag in here to call the id of new_image element from second_file.xml*/
    
    
    </LinearLayout>
    second_file.xml
    <LinearLayout
       android:id="@+id/linear_second"
       xmlns:android="<http://schemas.android.com/apk/res/android>"
       xmlns:tools="<http://schemas.android.com/tools>"
       xmlns:app="<http://schemas.android.com/apk/res-auto>"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="horizontal"
       >
    
       <ImageView
                android:id="@+id/new_image"
    			android:layout_width="wrap_content"
    			android:layout_height="wrap_content"
                app:srcCompat="@drawable/button_image"
    			/>
    
    </LinearLayout>
    m
    • 2
    • 3
  • w

    Will Nixon

    08/24/2020, 12:46 PM
    Hi all, tried to find an answer on Google/SO but not had much luck - I want to create a class that extends Constraint Layout so that I can add it dynamically to a view based on a toggle switch. I know that extending ConstraintLayout requires 3 constructor methods, but is there a way to pass in additional parameters when initializing the cutsom class? Ie. an array that I can then use in the custom class?
    m
    • 2
    • 4
  • c

    csturtevant

    08/24/2020, 8:40 PM
    Has anyone else here been running into long start up times for unit tests that use mockks? It takes 2-3 seconds compared to a unit test without mocks running in ~250ms. I’m on Kotlin 1.4.0 and Intellij 2020.2 with a JUnit 5 unit test. The goal is to have all unit tests running around ~300ms if possible. The mockk unit test is below:
    import io.mockk.every
    import io.mockk.mockk
    
    
    import org.junit.jupiter.api.BeforeEach
    import org.junit.jupiter.api.Test
    
    class ViewControllerTest {
    
        private val repository: TaskRepository = mockk()
        private lateinit var viewController : ViewController
    
        @BeforeEach
        fun setUp() {
            viewController = ViewController(repository)
            every { repository.findTasksFromView(any()) } returns emptyList()
        }
    
        @Test
        fun getView() {
            val list = viewController.getView(1)
            println(list)
        }
    }
    The regular unit test is here:
    import org.junit.jupiter.api.BeforeEach
    import org.junit.jupiter.api.Test
    import org.junit.jupiter.api.assertAll
    import kotlin.test.assertEquals
    
    internal class TaskTest {
    
        private val project: Project = Project(1, "Inbox","The default project", emptyList())
    
        @BeforeEach
        fun setUp() {
        }
    
        @Test
        fun `maps Task to Viewable using extension function`() {
            val task : Task = buildTask()
            val viewable : Viewable = task.toViewable()
            assertViewable(viewable)
        }
    
        private fun buildTask() : Task {
            return Task(
                    1,
                    "Get focused",
                    "TODO",
                    project
            )
        }
    
        private fun assertViewable(viewable: Viewable) {
            assertAll(
                    {assertEquals(1, viewable.id)},
                    {assertEquals("Get focused", viewable.name)},
                    {assertEquals("TODO", viewable.status)},
                    {assertEquals(project, viewable.project)},
            )
        }
    }
    Someone else is having the same issue on StackOverflow: https://stackoverflow.com/questions/62208145/why-is-mocking-so-slow-to-start-in-kotlin
    o
    t
    t
    • 4
    • 6
  • g

    gjesse

    08/25/2020, 2:08 PM
    this seems weird to me - i have a kotlin class that implements an interface by a delegate (using the
    by
    keyword). the interface is defined in java and has some 
    default
     methods. my class does not override those methods. i was expecting them to be forwarded to the delegate, but instead the default version is used. do i have to explicitly override all
    default
    methods in order to forward them to the delegate?
    d
    • 2
    • 12
  • k

    Kenneth

    08/26/2020, 9:49 AM
    Hi! What is the correct matcher for a parameter Supplier<T>?
    m
    • 2
    • 5
  • o

    Oleh Ponomarenko

    08/26/2020, 10:34 AM
    Hello! Is there method like in JavaScript match() which returns list by regex?
    m
    d
    • 3
    • 3
  • s

    Saul Wiggin

    08/26/2020, 1:26 PM
    Hello. just started learning Kotlin for a new android project. This is a great starter application https://github.com/mrcsxsiq/Kotlin-Pokedex and i've got IntelliJ running with a korge multiplayer plugin. Wonder if any veterans had any advice for learning materials, IDE extensions or start-projects?
    j
    • 2
    • 2
  • k

    Kenneth

    08/26/2020, 2:49 PM
    Is it possible to verify(mockk) a service that gets called which is inside a class inside a method of the class being tested?
    k
    • 2
    • 3
  • o

    oday

    08/26/2020, 4:46 PM
    how can I turn this back into a list after doing the operation in its lambda to each of the items in the list?

    https://i.imgur.com/g0mrTBN.jpg▾

    n
    k
    • 3
    • 10
  • z

    zero_coding

    08/26/2020, 7:23 PM
    Hi all Why do I need parentheses at the end of the following inheritance:
    class NoInterestsFound : RuntimeException()
    c
    t
    • 3
    • 4
  • z

    zero_coding

    08/26/2020, 8:39 PM
    It is common the define a data class like this:
    data class Connector(val url: String, val username: String, val pw: String) {
    
        fun connect(): Database = Database.connect(url, "com.impossibl.postgres.jdbc.PGDriver", username, pw)
    
    }
    n
    • 2
    • 1
  • o

    oday

    08/27/2020, 8:27 AM
    why would object (of a data class)
    .toString()
    not print its contents and only print the type?
    m
    • 2
    • 1
  • w

    Will Nixon

    08/27/2020, 3:32 PM
    Hi all - I’m trying to use SharedPreferences in my app in order to save a few preferences that then need to update pretty instantaneously inside the app. I have a settings page, where the user can switch from light to dark mode, and also update the voice of a TTS functionality. When the user ‘saves changes’ - I call editor.putXXXX(key, value).apply() for each setting and then close out of the settings page. Unfortuntately, I neither see the settings changed in my main activity, nor see the updated settings when I go back into the settings page. I understand that .apply() is asynchronous - I suspect that calling .apply() for each setting is going to cancel previous calls to .apply() - am I able to make several “puts” and then call .apply() just the once to make those several changes in one go? Why would I not see immediate changes in my main activity even if I call ‘sharedPrefs.getXXX’ again? I’m assuming it’s just an issue whereby the apply() function hasn’t actually finished yet? I’ve tried Googling and SOing for solutions but not getting anywhere
    m
    • 2
    • 1
  • z

    zero_coding

    08/27/2020, 7:26 PM
    with https://github.com/npryce/konfig????
    m
    • 2
    • 1
Powered by Linen
Title
z

zero_coding

08/27/2020, 7:26 PM
with https://github.com/npryce/konfig????
m

Matteo Mirk

08/28/2020, 8:17 AM
There’s only one way to do it, you just declare your configuration object including
EnvironmentVariables()
and you should be able to retrieve them using the square bracket notation
config[...]
, that’s it.
View count: 2