https://kotlinlang.org logo
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
  • m

    Moritz Post

    11/29/2021, 10:45 AM
    Is there a kotlin only replacement for the java method
    Character.getNumericValue()
    ? It would be useful in kmp but i can't seem to find one.
    j
    t
    i
    • 4
    • 8
  • a

    Alex Ostrovsky

    11/29/2021, 2:59 PM
    hello, on the https://discuss.kotlinlang.org/ website when trying to log in I accidentally selected the wrong Google account, and now I am not able to select the correct one because it keeps trying to get me to create that new account when I click "Log In". is there any way to "log out" of this non-existent half-created account?
    d
    • 2
    • 7
  • n

    Nick

    11/29/2021, 9:29 PM
    I’m going crazy getting my
    freeCompilerArgs
    working. I’m still getting errors/warnings with what I have tried below. This is in the
    build.gradle
    of a module.
    android {
        kotlinOptions.freeCompilerArgs += compilerArgs
    }
    and
    tasks {
        withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
            kotlinOptions.freeCompilerArgs += compilerArgs
        }
    }
    …. more in thread 🧵
    e
    j
    • 3
    • 11
  • c

    Colton Idle

    11/30/2021, 3:50 AM
    I have a list of people and each person has a TYPE. Either DIRECTOR, PROFESSOR or STUDENT. How do I sort the list so that all students are listed after the DIRECTORS and PROFESSORS? As a first approach to this, I think it would just be easier to just have two identical lists. filter out the students from list 1. and then filter out prof and directors from list2 and add them together.
    e
    u
    • 3
    • 12
  • l

    Leonardo Borges

    11/30/2021, 10:54 AM
    Hello! I don't know if this is the right place (didn't found any JVM specific channel). We have a Kotlin JVM service which is not attached to any web framework, such as Spring. Still, we want to standardize it with hexagonal architecture and I was wondering about dependency injection. I came across this lib (https://github.com/Kodein-Framework/Kodein-DI/). Has someone used? Is there any other alternative?
    r
    s
    h
    • 4
    • 3
  • j

    Jan

    11/30/2021, 1:26 PM
    I'm not sure what this error is trying to tell me:
    Exception in thread "DefaultDispatcher-worker-3" java.lang.ClassCastException: class kotlin.reflect.jvm.internal.KTypeImpl cannot be cast to class kotlin.jvm.internal.TypeReference (kotlin.reflect.jvm.internal.KTypeImpl and kotlin.jvm.internal.TypeReference are in unnamed module of loader 'app')
    at kotlin.jvm.internal.ReflectionFactory.mutableCollectionType(ReflectionFactory.java:107)
    at kotlin.jvm.internal.Reflection.mutableCollectionType(Reflection.java:196)
    at io.github.jan.discordkm.api.entities.interactions.commands.builders.ChatInputCommandBuilder.build$DiscordKM(ApplicationCommandBuilder.kt:211)
    at io.github.jan.discordkm.api.entities.containers.CommandContainer.create(CommandContainer.kt:29)
    at io.github.jan.therealbot.MainKt$main$$inlined$on$default$4.invokeSuspend(DiscordWebSocketClient.kt:171)
    at io.github.jan.therealbot.MainKt$main$$inlined$on$default$4.invoke(DiscordWebSocketClient.kt)
    at io.github.jan.therealbot.MainKt$main$$inlined$on$default$4.invoke(DiscordWebSocketClient.kt)
    at io.github.jan.discordkm.api.events.EventListenerKt$EventListener$1.onEvent(EventListener.kt:21)
    at io.github.jan.discordkm.api.events.EventListener$DefaultImpls.invoke(EventListener.kt:16)
    at io.github.jan.discordkm.api.events.EventListenerKt$EventListener$1.invoke(EventListener.kt:20)
    at io.github.jan.discordkm.api.entities.clients.DiscordWebSocketClient$handleEvent$2$1$1.invokeSuspend(DiscordWebSocketClient.kt:101)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:571)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:678)
    at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:665)
    r
    • 2
    • 4
  • c

    Colton Idle

    11/30/2021, 7:20 PM
    Not super comfortable with sealed classes. I'm trying to model an action type that can model things like a phone button click, or a url click, or unhandled (unknown). How does this look?
    sealed class GenericActionType {
        class Dialer(phoneUri: String) : GenericActionType()
        class Browser(url: String) : GenericActionType()
        object Unknown : GenericActionType()
    }
    j
    l
    +2
    • 5
    • 8
  • t

    thana

    12/01/2021, 11:07 AM
    Hi, in a situation like this: https://pl.kotl.in/vK8g6iJtG is there a way to implement this interface while keeping the
    username
    part of the primary ctor and without changing its name?
    j
    n
    • 3
    • 8
  • p

    Pratik Khandelwal

    12/01/2021, 12:04 PM
    Hi all, I’m fairly new to Kotlin. I’m trying to implement the below code. The
    getCurrentSubscription
    method returns a `Subscription?
    nullable type. Doing a
    .let` makes the
    it
    also type of
    Subscription?
    . I though .let should pass on a non-null
    Subscription
    inside. Now my
    cancelSubscription
    method expects a non-nullable
    it.id
    which is causing issues. What am I missing here?
    getCurrentSubscription.invoke(customerId).let {
          cancelSubscription.invoke(it.id, cancelled).let { subscription ->
            subscriptionApiMapper.fromDomainModel(subscription)
          }
        }
    r
    • 2
    • 2
  • e

    elect

    12/01/2021, 12:54 PM
    today lesson is about some witchcraft.. how the hell can they at Facebook have such a syntax:
    typealias BatchSize = 100
    typealias Height = 40
    typealias Width = 50
      
    fun getFirst(
      input: Tensor<[BatchSize, Height, Width]>
    ): Tensor<[Height, Width]> {
     ...
    }
    typealias
    integer values or square brackets in type parameters..?
    • 1
    • 1
  • a

    Ahmed Hassan

    12/01/2021, 1:04 PM
    if (nullableVarParent?.nullableValChildOne == null
             || nullableVarParent?.nullableValChildTwo == null) 
          return
        
    funcEx(
         nullableVarParent?.nullableValChildOne!!,   
         nullableVarParent?.nullableValChildTwo!!
    )
    ...
    I had a discussion with a college about how unsafe the previous code is, to use (!!) operator even after "if condition". He is totally convinced that the mutable parent is impossible to be null after the if condition since we don't use threads in this area. His words are some how believable but since everyone in the world has been saying to avoid suppression (!!) in all cases, I wanted to make sure. what do you think might be dangerous about this?
    r
    k
    m
    • 4
    • 6
  • a

    Ahmed

    12/01/2021, 3:18 PM
    hey guys, what is the equavilant of this python code
    s = "string"
    list = [s * 10]
    basically, I just want to create a list of objects each of them is the same string actually
    j
    k
    • 3
    • 3
  • r

    Richard Gomez

    12/01/2021, 9:53 PM
    I've encountered a strange type mismatch error with 1.5.31 and am not sure if it's a bug. Consider the code in the attached snippet. The
    compiles
    method compiles without issue, but if I save the expression to a variable instead of returning it, it complains about a type mismatch.
    sample.kt.cpp
    c
    i
    • 3
    • 9
  • h

    hoang

    12/02/2021, 8:46 AM
    I've got this generic function: https://pl.kotl.in/cv6sdbHHy
    j
    • 2
    • 6
  • a

    Ayfri

    12/02/2021, 3:45 PM
    Hi, I want to parse a simple date, and I don't know why this doesn't work
    val versionDate =  "May 5, 2009"
    	val formattedDate = SimpleDateFormat("MMM d, yyyy").parse(versionDate)
    	println(formattedDate)
    What am I doing wrong ?
    k
    r
    +2
    • 5
    • 18
  • c

    Colton Idle

    12/03/2021, 3:06 PM
    I have a behavior that I want a majority of my ViewModel classes to support. I considered creating a BaseViewModel, but I have also seen base classes that get out of control with if statements everywhere, and then it becomes clear that a base class wasn't the right approach. I have seen the statement "favor composition over inheritence", but I haven't seen a practical example of it ever (or maybe I just never connected the dots). How would I make a class have this sort of behavior be composable (not to be confused with jetpack compose) instead of using inheritence? Do I just use interfaces since I can define multiple interfaces to implement? (I know that this is sort of not necessarily kotlin, but I figured it'd be worth a shot asking here)
    d
    a
    d
    • 4
    • 7
  • j

    Jesse Hill

    12/03/2021, 4:18 PM
    I was just experimenting with the
    String.split
    functionality and came across this situation which made me curious. I found that running this:
    "hello".split("")
    produces this
    ["", "h", "e", "l", "l", "o", ""]
    . I didn’t expect for there to be empty strings on the start and end of the returned list only that the list would be made up of each character from the original string. To clarify, I’m not asking about the best way to iterate characters in a string or how to get them into a list, just curious about the implementation of
    split
    with an empty separator and why the empty strings were appended to each end of the resulting list?
    v
    k
    • 3
    • 3
  • f

    Filipe Duarte

    12/04/2021, 1:02 PM
    I want to do parallel computations over collections and do parallel for loops. Java Streams with parallel for the first case? And the second case?
    g
    • 2
    • 5
  • e

    Edoardo Luppi

    12/04/2021, 1:48 PM
    The Kotlin plugin reports private properties overriding public methods of extended Java classes. Does anyone encounter the same issue?
    p
    • 2
    • 2
  • a

    Alex

    12/04/2021, 3:59 PM
    Is it normal to spend more then a month trying to understand generics?😅
    👍 2
    j
    a
    k
    • 4
    • 4
  • t

    TwoClocks

    12/04/2021, 8:02 PM
    I'm not sure I follow the use case for Kotlin's
    Duration
    it seems to be missing
    .between
    ? So I need to use Java's, in which case I can't use Kotlin's because importing both doesn't work? What am I missing?
    e
    d
    • 3
    • 9
  • c

    Colton Idle

    12/04/2021, 8:05 PM
    I'm trying to convert a long amount in euro cents to a readable value. I'm not European and I see conflicting information on this. Here is my ext func
    fun Long.euroCentsToString(): String {
        val format = NumberFormat.getCurrencyInstance()
        format.maximumFractionDigits = 2
        format.currency = Currency.getInstance("EUR")
    
        return format.format(this/100)
    }
    If I call
    849999L.euroCentsToString()
    I get a result of
    €8,499.00
    I thought what I'd get is
    €8.499,99
    So Basically three issues: 1. I thought europeans use
    .
    to separate thousands from hundreds 2. I thought europeans use
    ,
    to designate the start of fractional (cents) 3. I thought I'd see 99 as the cents and not 00.
    t
    e
    • 3
    • 37
  • a

    Ayfri

    12/05/2021, 2:58 PM
    Hi, I'm doing advent of code 2021 and I have a very very very weird bug where my console is broken and only display a fraction of the lines, when I execute this code :
    val data = readFile("day1.txt")
    val pairs = data.trimEnd().split("\n").zipWithNext().toMap()
    val result = pairs.count { a ->
    	return@count a.key == a.value
    }
    	
    pairs.forEach { println("key=${it.key}, value=${it.value}") }
    	
    println(result)
    I don't get the
    key=something
    part in my console
    e
    • 2
    • 9
  • d

    Draget

    12/05/2021, 8:41 PM
    If I define a function outside a class and want to access it with reflection, under which 'class' do I find it?
    t
    e
    • 3
    • 5
  • h

    holgerbrandl

    12/05/2021, 10:51 PM
    Hey, how could I calculate a run length encoding elegantly for arbitrary types (not just strings but based on
    equals
    ). E.g. how to transform
    listOf("A", "A", "B", "C", "C", "C", "C", "A", "A")
    // to
    listOf("A" to 2, "B" to 1, "C" to 4, "A" to 2)
    e
    s
    • 3
    • 7
  • m

    Marc Javier

    12/05/2021, 10:59 PM
    groupingBy method
    e
    h
    m
    • 4
    • 9
  • m

    Minsoo Cheong

    12/07/2021, 9:15 AM
    hi everyone, Q: Do 'Sealed (exhaustive) 
    when
     statements' break OCP(open-closed-principle) ? I saw the new sealed when compiler feature on Kotlin 1.6.0 and shared it to my team, thinking we could use it, but there was an opinion that this kind of logic breaks the ocp rule because, If you add new inheritors to the sealed class(or interface), you would have to change all the when statements that take that sealed class(which is the parent class) and thus, ocp is broken Would this be true? We agreed that the oop rules were made before sealed classes/interfaces were introduced and this might be the "trend" of programming languagues, but still some are hesitant to use it. Any kind of related opinion & reading material is welcome to be shared,, thanks!
    a
    j
    +3
    • 6
    • 10
  • p

    Pitel

    12/07/2021, 9:23 AM
    Is there some way to create range withou having to sort it first? I mean,
    10..0
    creates empty range, and I have to change it to
    10 downTo 0
    . But I don't want to bother with it. I would expect
    10..0
    to do it automaticaly.
    s
    s
    • 3
    • 2
  • a

    Alex K

    12/07/2021, 8:27 PM
    If I have a string array: ```<string-array name="listOfNorthDishesArray"> <item>{"name":"Khai Paen","details":"River weed is turned into thick, simmered, spicy sauce or dried in thin sheets which have been sprinkled with tamarind and ginger juice and other aromatics such as sesame seeds, tomato and garlic. The dry sheets are cut into small squares and flash shallow fried for a tasty drinks snack."} </item> <item>{"name":"Jeow Bong","details":"Jeow bong is eaten with fried or grilled river algae sheets kai paen or kai phene, grilled dried beef gee sin lod or steamed vegetables. It is also served as an accompaniment to sticky rice or added to stir fries."} </item> </string-array> how can I return just "name" here
    resources.getStringArray(R.array.listOfNorthDishesArray).toMutableList()
    :not-kotlin: 4
    j
    • 2
    • 1
  • n

    Nick

    12/07/2021, 11:40 PM
    Is it good practice to keep your sealed/data classes outside of the class that uses it, or is it better to keep it inside? 1️⃣
    class MyViewModel : ViewModel() {
        sealed class SelectedFolder {
            object Unselected : SelectedFolder()
            data class Selected(val id: String) : SelectedFolder()
        }
    }
    or 2️⃣
    private sealed class SelectedFolder {
        object Unselected : SelectedFolder()
        data class Selected(val id: String) : SelectedFolder()
    }
    
    class MyViewModel : ViewModel() {
    2️⃣ 1
    h
    s
    m
    • 4
    • 4
Powered by Linen
Title
n

Nick

12/07/2021, 11:40 PM
Is it good practice to keep your sealed/data classes outside of the class that uses it, or is it better to keep it inside? 1️⃣
class MyViewModel : ViewModel() {
    sealed class SelectedFolder {
        object Unselected : SelectedFolder()
        data class Selected(val id: String) : SelectedFolder()
    }
}
or 2️⃣
private sealed class SelectedFolder {
    object Unselected : SelectedFolder()
    data class Selected(val id: String) : SelectedFolder()
}

class MyViewModel : ViewModel() {
2️⃣ 1
I think I prefer 1️⃣ because it is clear in that class what’s going to be used and organizes it a bit more i think?
h

Haris Khan

12/08/2021, 1:14 AM
I personally use #2 to make my classes a bit easier to follow
s

Stephan Schroeder

12/08/2021, 7:44 AM
I never used #1, used to use #2, but nowadays I don't even put the children of the sealed class within the sealed class (mainly because it makes referencing the children shorter,
is Selected
instead of
is SelectedFolder.Selected
) On the other hand, i've never wrote a private sealed class 🤔
sealed class SelectedFolder
object Unselected : SelectedFolder()
data class Selected(val id: String) : SelectedFolder()

class MyViewModel : ViewModel() {
👍 1
m

Michael de Kaste

12/08/2021, 10:37 AM
we put sealed classes as seperate files just like we would enums. But that's mostly because these sealed classes are used throughout the project or module. unlike @Stephan Schroeder, I prefer nested values for the sealed class. I like treating the sealed class as an enum. The on the fly import assist helps us in immediatly abstracting away the parent selector, just like with enums, but we can still do
SelectedFolder.
and get a list of its children as suggestions.
➕ 1
View count: 9