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

    Kenneth

    08/28/2020, 7:58 AM
    What is the default indentation for Kotlin in intellij?
    m
    2 replies · 2 participants
  • d

    Daniele B

    08/28/2020, 8:21 PM
    what is the difference between these two annotations? @OptIn(ExperimentalCoroutinesApi::*class*) @ExperimentalCoroutinesApi
    e
    3 replies · 2 participants
  • v

    Valentin Metz

    08/29/2020, 5:31 AM
    How can I align console output in Kotlin?
    488 -> 488	| 485/500
    489 -> 44499	| 486/500
    490 -> 70070	| 487/500
    491 -> 8838	| 488/500
    492 -> 3444	| 489/500
    493 -> 7888	| 490/500
    494 -> 494	| 491/500
    496 -> 992	| 492/500
    497 -> 994	| 493/500
    480 -> 60000	| 477/500
    460 -> 2202020	| 496/500
    499 -> 499	| 497/500
    498 -> 996	| 495/500
    495 -> 990	| 494/500
    483 -> 966	| 480/500
    500 -> 500	| 498/500
    290 -> 11011010	| 499/500
    430 -> 11011010	| 500/500
    d
    15 replies · 2 participants
  • z

    zero_coding

    08/29/2020, 7:08 AM
    Hi all Could someone please tell me, how can I make the following code more elegant:
    class GenderMapper(val id: String, val description: String)
    
    fun GenderMapper.toGender(): Gender {
        val description = this.description
        return Gender.new(id) {
            this.description = description
        }
    }
    j
    t
    6 replies · 3 participants
  • z

    zero_coding

    08/29/2020, 2:52 PM
    What does
    UUID!
    mean?
    d
    r
    +1
    6 replies · 4 participants
  • v

    Valentin Metz

    08/29/2020, 7:08 PM
    I'd like to have an array of ~1000 Functions (not all are implemented yet) to choose one from at runtime and pass all input arguments (after the first, which is used to choose the function) to. How can I create the array and call from it?
    m
    m
    11 replies · 3 participants
  • v

    Valentin Metz

    08/30/2020, 9:05 PM
    I'm running into an error with my UnitTests. Can't really make sense of the errormessage: - Is this an issue with gradle? The only test atm is a simple @Test assert(true). https://pastebin.com/GZXsiDWL
    j
    4 replies · 2 participants
  • a

    Alexey Anufriev

    08/31/2020, 6:34 PM
    hey guys, question about idiomatic syntax what is preferable, this
    if (event == null) {
        return emptyArray()
    }
    or this
    event ?: return emptyArray()
    ? note: this is just the first line of the method, then comes more logic
    1️⃣ 2
    n
    s
    4 replies · 3 participants
  • k

    Karlo Lozovina

    09/02/2020, 1:01 PM
    is there something like
    TODO("reason")
    but meant just for unreachable `if`/`when` branches? (for example like Rust has
    unreachable!
    macro do designate code paths that can't be taken)
    d
    m
    +1
    5 replies · 4 participants
  • p

    Pau

    09/02/2020, 4:14 PM
    Hi guys, I hope all of you are having a good one! I am doing some projects from Hyperskill, concretely the minesweeper. I managed to create a 2D array which randomly locates mines. After this, I created another array to shows in each position how many mines are around the coordinate. As the array is char, I need to convert the number of mines around the coordinate into a char and here I have the issue. The program runs without any problem but it does not show what it should. Is this some issue I cause?
    X is mine
    . there are not mines around
    m
    m
    8 replies · 3 participants
  • p

    Patrick Ramsey

    09/02/2020, 4:49 PM
    The project seems to build fine, and I see it downloading that library, but it then doesn't seem to be in my class path. I feel like I must be skipping some obvious step.
    e
    2 replies · 2 participants
  • e

    Eugene Freeman

    09/02/2020, 7:49 PM
    Hi there Is kotlin coroutines based on the java nio or they have their own implementation of non-blocking io?
    n
    e
    +1
    23 replies · 4 participants
  • w

    Wesley Acheson

    09/03/2020, 11:54 AM
    really simple question. Trying to create a java object that requires setters to be called. Is this the right pattern to use or not
    val jsonHeader = HttpHeaders().let {
            it.accept = listOf(MediaType.APPLICATION_JSON)
            it
        }
    t
    f
    +1
    15 replies · 4 participants
  • d

    Daniele B

    09/03/2020, 3:48 PM
    Let’s say I have a
    data class
    object:
    val state : AppState = AppState()
    where:
    data class AppState (
      val loginState : LoginState = LoginState(),
      val showingDetail : Boolean = false,
    )
    data class LoginState (
      val loginVar : String
    )
    if I want to just change a child property, it’s very simple, it just takes 1 line:
    state = state.copy(showingDetail = true)
    but it I want to change the property of one child, I need 3 lines:
    var login = state.loginState
    login = login.copy(loginVar = "my value")
    state = state.copy(loginState = login)
    is there a simpler syntax to achieve this?
    t
    a
    28 replies · 3 participants
  • d

    Daniele B

    09/03/2020, 8:42 PM
    I have a list of these objects
    class MyDataObj (
    	var a : Int
    	var b : Int
    	var c : Int
    )
    What is the most simple way to get an object of the same class, where each variables are the sum of variables of the elements in the list?
    a
    1 reply · 2 participants
  • d

    Daniele B

    09/03/2020, 8:45 PM
    so, if:
    val obj1 = MyDataObj(1,3,4)
    val obj2 = MyDataObj(3,2,3)
    val obj3 = MyDataObj(2,4,1)
    val list = listof(obj1,obj2,obj3)
    I would like to derive
    objTot
    , which has a=6, b=9, c=8
    e
    c
    5 replies · 3 participants
  • d

    Daniele B

    09/03/2020, 10:11 PM
    I have a static list defined in my project. Like this:
    val obj1 = MyDataObj(1,3,4)
    val obj2 = MyDataObj(3,2,3)
    val obj3 = MyDataObj(2,4,1)
    val list = listof(obj1,obj2,obj3)
    using AndroidStudio/IntelliJIdea, is it possible to run a script, where I experiment a reduce function, without having to run the whole project, but just this script which references an objected defined in my project? In other words, can I run my “playground” inside my IntellijIDEA, which references classes already defined in a projects? I would like to run something like this
    println(list.sumBy{ it.a })
    n
    6 replies · 2 participants
  • e

    Eugene Freeman

    09/04/2020, 6:01 PM
    Hi there Is there any legal way to convert
    private suspend fun containsMatchIn(contentMessage: ContentMessage<*>): Boolean {
            val content = contentMessage.content
            return ((content is TextContent) && !hasCommand(content) && containsInText(content.text))
                    || ((content is PhotoContent) && containsInImage(content))
        }
    into
    private suspend fun containsMatchIn(contentMessage: ContentMessage<*>): Boolean {
            return ((contentMessage.content is TextContent) && !hasCommand(contentMessage.content) && containsInText(val content = contentMessage.content.text))
                    || ((contentMessage.content is PhotoContent) && containsInImage(contentMessage.content))
        }
    to get rid of the extra variable
    val content = contentMessage.content
    ? Thanks
    n
    a
    5 replies · 3 participants
  • d

    dan

    09/05/2020, 9:41 AM
    Hi everyone, I have this simple code and it doesn't run as expect. I want to add an element to an array of int and then I expect it will have 1 element. The current code print 0
    val res : Array<Int>  = emptyArray()
     res.plus(1)
     println(res.size)
    p
    r
    9 replies · 3 participants
  • w

    Wesley Acheson

    09/05/2020, 12:44 PM
    Whats the correct way to document an enum class?
    /**
         * Represents the way two [clauses][Clause] are joined.
         *
         * @property AND Means that this clause and the previous clause should be combined using and
         * (i.e. both need to be `true`)
         * @property OR Means that this clause should be combind with the previous clause using or
         * (i.e. this clause needs to be true or the previous clause needs to be `true`)
         */
        enum class Conjunction() {
            AND,
            OR
        }
    Or should the values be on the enums themselves?
    n
    6 replies · 2 participants
  • b

    BearDev

    09/07/2020, 12:19 AM
    Hey, I am migrating my project to kotlin 1.4 and I started running into compiler running out of memory
    > Task :compileKotlinJvm FAILED
    
    e: java.lang.OutOfMemoryError: Java heap space
    So far I have tried to adjust
    Build process heap size
    upwards to 8000 megabytes, and have tried to provide a max memory flag of 8g to build process VM options. Neither attempt seemed to make any difference, as the compiler process seems to still max out at around 850mb when it throws an Out of memory exception. Any help would be greatly appreciated.
    e
    1 reply · 2 participants
  • e

    Emery Tanghanwaye

    09/07/2020, 5:17 AM
    Hey all, just wondering, why is kotlin stuck on Java 8? Why doesn't it start targeting newer versions?
    e
    m
    +1
    10 replies · 4 participants
  • d

    Dan O'Brien

    09/07/2020, 2:19 PM
    does anyone have any suggestions for how to handle comparing 2 similar(but not exact) lists. I want to compare the objects in list(generally in same position in either list) A by
    key
    against list B, and then by a
    version
    . If value in list B is higher than list A, I want to replace list A with item from list B. I think
    compareValuesBy
    might work but I’m having trouble sorting out how to implement it fully because elements might be slightly different so I’ll need to scan the list to verify if it’s not found
    n
    2 replies · 2 participants
  • d

    Daniele Segato

    09/08/2020, 3:38 PM
    what do you guys use for mocking in kotlin? I've been using mockito since forever... but with kotling i've run into issues with suspending functions
    `when`<Asset>(adapter.assetGetToAsset(input))
       .then {
           delay(300L)
           output
       }
    this simple thing I can't do because
    then
    doesn't give me a coroutine context. Do you use Mockk? Some other libraries? What are the pros and cons? Bonus question: is there some best practice to test when you have final classes? (which are the default in kotlin).
    c
    m
    9 replies · 3 participants
  • d

    Dan O'Brien

    09/09/2020, 1:00 AM
    is there something I’m completely missing about using a while loop within a for loop? The while loop is looping over a list of JSwing nodes, the for loop is iterating over a list of items but the for loops only runs a single time then just does not loop, I don’t get it. I originally tried a foreach, and now I’m just adding print statements to try to understand what I’m doing wrong. I know this code is not the cleanest/most correct lol. Learning Kotlin as I go
    Untitled
    m
    n
    15 replies · 3 participants
  • m

    Miguel Quinta

    09/10/2020, 11:39 AM
    Hi all! I have a basic doubt but I'm stuck with it... How can I continue and accept an empty input? using this: val scanner = Scanner(System.in) val myNum = scanner.nextInt() I must always insert a number for programm to continue. But I wanted to insert nothing and just press enter for the programm to continue. And this way, myNum val would be empty been googling it, but I think I'm not knowing how to search for it correctly..
    m
    3 replies · 2 participants
  • d

    Dan O'Brien

    09/10/2020, 12:26 PM
    can anyone help me with:
    e: /home/runner/work/intellij-plugin-ld/intellij-plugin-ld/src/main/kotlin/com/github/intheclouddan/intellijpluginld/settings/LaunchDarklySettings.kt: (155, 21): Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
    public fun <T> MutableCollection<in ???>.addAll(elements: Array<out ???>): Boolean defined in kotlin.collections
    public fun <T> MutableCollection<in ???>.addAll(elements: Sequence<???>): Boolean defined in kotlin.collections
    public fun <T> MutableCollection<in String!>.addAll(elements: Iterable<String!>): Boolean defined in kotlin.collections
    I’ve tried assigned it to a variable and suppressing that as Unused, I’ve wrapped that section with a
    with
    block but nothing so far is helping me with this error. Here’s a link to the line in the repo https://github.com/InTheCloudDan/intellij-plugin-ld/blob/master/src/main/kotlin/com/github/intheclouddan/intellijpluginld/settings/LaunchDarklySettings.kt#L155
    m
    i
    8 replies · 3 participants
  • s

    Skaldebane

    09/10/2020, 8:19 PM
    #introduce-yourself Hello Everybody! My name is Hossam Elbadissi, and my nickname on the web is "Skaldebane". I'm a 16 years old High School student in Morocco, and I've recently switched to Kotlin from Java (a month ago)... Kotlin's amazing features, easy syntax and idiomatic coding made me fall in love with it, and the transition to it was pretty smooth due to its simplicity and similarity to Java. I mostly develop Android applications, though I also like to tinker around with other technologies and try new things... Glad to be here with you, and I'd like to learn more about everything Kotlin, and help shape the future of KotlinLang as it helped me shape mine, in a way or another. Thanks a lot JetBrains, for this amazing language!
    👍 4
    n
    m
    2 replies · 3 participants
  • s

    Steven Wang

    09/11/2020, 5:20 PM
    how to perform cumProd() operation over a list?
    n
    s
    7 replies · 3 participants
  • s

    Steven Wang

    09/12/2020, 5:24 PM
    val actuallObj: List<*> = listOf("a", "b")
    how to get the contained object type (String here) ?
    n
    n
    +1
    8 replies · 4 participants
Powered by Linen
Title
s

Steven Wang

09/12/2020, 5:24 PM
val actuallObj: List<*> = listOf("a", "b")
how to get the contained object type (String here) ?
n

nanodeath

09/12/2020, 5:37 PM
Java has type erasure, so you can't actually do that
n

nfrankel

09/12/2020, 5:45 PM
i’m not sure i understand your question as @nanodeath wrote, it’s not possible to get the type at runtime because of type erasure otherwise, it’s inferred at compile-time by the kotlin compiler
val actuallObj = listOf("a", "b")
actually, the type is
List<String>
val actuallObj: List<String> = listOf("a", "b")
actually, you’re actually removing type information with your syntax 😅
👆 1
m

Matteo Mirk

09/14/2020, 4:00 PM
You can’t for the list as a whole, but with reflection you can actually retrieve the runtime type of each element.
s

Steven Wang

09/14/2020, 4:56 PM
Thanks for helping out guys!! yes, I end up just check first element in my list as I knew I added them with same type. That worked out for me
n

nanodeath

09/14/2020, 4:58 PM
if that works, great 👍 watch out for polymorphic types
m

Matteo Mirk

09/15/2020, 8:07 AM
@Steven Wang Just out of curiosity: if you have all elements of the same type, why can’t you declare the list with a bounded type parameter? Like
List<String>
?
s

Steven Wang

09/15/2020, 10:13 AM
I was using krangl, one of the column I put in data with type
LocalDateTime
krangl dataframe will assign it as
AnyCol
, it will be convenient to know which column is
LocaldateTime
which I can convert to
ZonedDateTime
and plot as x-axis
m

Matteo Mirk

09/15/2020, 11:16 AM
Oh I see, you’re constrained by a library. Thanks for explaining
View count: 2