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

    kqr

    05/20/2022, 6:50 PM
    val x = if (y != null) y else {
        <http://log.info|log.info>("bla")
        z
    }
    vs
    val x = y ?: run {
        <http://log.info|log.info>("bla")
        z
    }
    a
    e
    e
    • 4
    • 4
  • t

    Tim

    05/21/2022, 3:43 PM
    Hi all, I reached the point where I would like to share code between two projects of mine. I assume it must be somehow possible to extract it into a (nonpublic) library and add that as a dependency in gradle. Is there a good guide / tutorial about how this can be achieved?
    :not-kotlin: 2
    r
    r
    +2
    • 5
    • 5
  • o

    Okan Yıldırım

    05/22/2022, 5:42 PM
    Hey, do I need to do something like this for extending?
    class NotAuthenticatedError(
       override val message: String,
    ) : Error(message = message)
    I mean can’t I basically use the message immediately because it is extending?
    j
    c
    • 3
    • 3
  • o

    Okan Yıldırım

    05/22/2022, 7:14 PM
    I also would like to ask how can I forward annotations For example: Instead of doing;
    @PreAuthorize("hasRole('user')")
    I would like to do
    @UserOnly
    j
    • 2
    • 2
  • u

    ursus

    05/23/2022, 2:43 PM
    What’s the reason that I cannot typealias a nested class?
    typealias BR = foo.bar.base.R
    if I then use
    BR.
    I don’t see
    string
    ,
    drawable
    etc I can only do
    typeealias BR_string = foo.bar.base.R.string
    typyealias BR_drawable = foo.bar.base.R.drawable
    etc, which is stupid
    e
    t
    • 3
    • 14
  • c

    CanOfBees

    05/23/2022, 5:26 PM
    Hi all - I'm working through the JetBrains Academy course on Kotlin and I have a dumb question. I'm at the early point of looking at the output of
    val result = println("text")
    println(result)
    
    text
    kotlin.Unit
    One of the practice questions asks about the Magic Of
    println
    and it implies that the value of
    result
    is
    Unit
    . While that's true, what's "text" doing in the output? Maybe this is something that I don't need to be worried about (and I'm not) but I'm curious why. println is called twice, once for "text", and then a second time for
    println
    itself, and the type value of the
    println
    function is
    kotlin.Unit
    ? Is that true for all functions? Just
    println
    ? Thanks for any clarity you're willing to share!
    v
    j
    • 3
    • 7
  • j

    Jordan Carlyon

    05/24/2022, 3:41 PM
    I am having some trouble with visibility modifiers. Basically I want a public getter method with a private setter for subclasses of a parent class. The issue is if that parent class has a private variable it is not able to be set from the child classes so I have to have the parent have a public variable for the child classes to use it but now the var is public so the getter is useless. In Java this was possible with the package-private modifier which in Kotlin has been changed to module-private so do I really need to create a new module just to hide some
    vars
    ?
    e
    c
    c
    • 4
    • 71
  • j

    Jonathan Ellis

    05/24/2022, 7:04 PM
    is there some heuristic whereby it makes sense that collections.last() is a function but size is a property?
    e
    y
    • 3
    • 5
  • j

    Jonathan Ellis

    05/24/2022, 7:08 PM
    and on the math side, absolutevalue is a property of Double, pow is a method of Double, and sqrt is a standalone function in the math package
    e
    • 2
    • 1
  • t

    tipsy

    05/24/2022, 7:40 PM
    is there any way to get html syntax highlighting on a kotlin template string in intellij?
    e
    • 2
    • 3
  • a

    Antonio Acuña Prieto

    05/25/2022, 6:55 PM
    Hello guys, hope you can help me with this. I have a function that deletes an element of a list, something like:
    fun delete(id: UUID) = list.removeIf { it -> it.id == id }
    And I want to: • If the element was removed, don’t return nothing. • If the element was not found, return exception For now I have something like:
    fun delete(id: UUID) = takeIf { list.removeIf { it -> it.id == id } } ?: throw NotFoundException(id)
    But this still returns a true.
    v
    e
    p
    • 4
    • 4
  • z

    zain

    05/26/2022, 6:15 AM
    Hello I want to write a regex the checks if the string contains the following characters ' " | \ / <>:
    "Team's<>".contains("/[\"'\\/\\\\<>;|]/;")
    n
    • 2
    • 1
  • c

    CanOfBees

    05/26/2022, 3:39 PM
    Hi all - another "what are the expectations here?" question based on a question in the JetBrains' hyperskill Kotlin course. I have a question that asks: "what are the expected inputs for the following snippet of code:"
    val scanner = Scanner(System.`in`)
    val s1 = scanner.nextLine()
    val s2 = scanner.nextLine()
    val num = scanner.nextInt()
    The answers are roughly: a )
    ABC DEF
    123
    b )
    ABC
    DEF 123
    c)
    10
    ABC
    3
    d)
    ABC DEF 123
    Looking the behavior in kotlin file locally, the only answer that doesn't throw an error is
    a
    , but not according to the course page. Is this a Kotlin version issue? A JVM issue? Apparently the correct answer is
    c
    but the first Int is confusing me. Any hints or clarity would be most appreciated! Thank you!
    j
    p
    +2
    • 5
    • 14
  • a

    Ankush

    05/26/2022, 6:19 PM
    #getting-started - I am new to Kotlin and trying to absorb as much as possible. I have a requirement where I have a Multi-Level List that I need to parse up to 4 levels. List<List<List<List<String>>>>. The typical way would be using 4 for loops and keep iterating, but I am looking for a smarter Kotlin way of doing it. Could you guys please help me get there?
    for(a in As){
        for(b in Bs){
            for(c in Cs){
                for(d in Ds){
                    
                }
            }
        }
    }
    Another train of thought I have is to use flatMap() to flatten the last loop and drop the loops from 4 to 3. But there too, am getting beaten up by Kotlin syntax. Any help is appreciated! TIA 🙂 EDIT: Sturcture is of complex type in nature:
    data class A(
        val b: List<B>
    )
    data class B(
        val c: List<C>
    )
    data class C (
        val d: List<D>
            )
    data class D(
        val string1: List<String>,
        val string2: String
    )
    🙂 1
    c
    e
    • 3
    • 15
  • k

    Karlo Lozovina

    05/27/2022, 5:27 PM
    Are there other languages with feature similar to Kotlin's inner claseses?
    a
    e
    • 3
    • 6
  • j

    Joseph Burton

    05/27/2022, 8:34 PM
    Why does this error occur? I thought the
    contract
    should prevent it
    👍 1
    d
    • 2
    • 2
  • s

    smit01

    05/28/2022, 10:52 AM
    val invoke: suspend ()->Unit = fun(){}
    Shows this error is it possible to declare suspending anonymous function with fun keyboard. I am also aware of suspending lambda that's not my question. Thanks in advance.😇 error type mismatch: inferred type is () -> unit but suspend () -> unit was expected (line_27.kts1️⃣32)
    y
    • 2
    • 1
  • m

    martmists

    05/28/2022, 4:44 PM
    In this snippet, sequence{} knows its in the
    parens
    rule if you check prop.name in getValue or provideDelegate, but is there a way the resolve() call could get access to this information somehow? I checked the stack trace and couldn't really find anything that could give this information
    e
    j
    • 3
    • 7
  • e

    Ellen Spertus

    05/29/2022, 3:54 PM
    I am having trouble understanding some code I saw of the form:
    fun myfun: Boolean {
      return foo?.stringProperty.isNullOrEmpty()
    }
    It seems to me that this would return
    null
    , which is not
    Boolean
    when
    foo
    is
    null
    . Why is the above code legal?
    s
    f
    • 3
    • 3
  • n

    Nick

    05/29/2022, 7:19 PM
    I’d like to create a scheduler app that contains a list of events. Each event has a
    startDate
    and an
    endDate
    . I’d like to determine which events overlap so I can place events in a different column. Is there a way to apply some sort of
    groupBy
    function to accomplish a way for me to group them?
    p
    • 2
    • 2
  • m

    Mark

    05/30/2022, 1:03 AM
    Which type would you use to represent a single digit
    [0-9]
    ? 1️⃣ Int 2️⃣ UInt 3️⃣ Byte 4️⃣ Short 5️⃣ value class of Int 6️⃣ value class of UInt 7️⃣ value class of Byte 8️⃣ value class of Short 9️⃣ value class of Char I suppose we already have the Kotlin answer, which is
    Char.digitToInt(): Int
    c
    e
    +2
    • 5
    • 8
  • k

    Kirill Grouchnikov

    05/30/2022, 1:07 AM
    DigitFactoryContentProviderAdapterBridge
    🤔 1
    ⁉️ 1
    m
    • 2
    • 1
  • m

    Mark

    05/30/2022, 8:40 AM
    Please can someone explain what is happening here: https://pl.kotl.in/3lF-S9LUl
    var check1 = true
    var check2 = false
    val test = if (check1) {
        null
    } else if (check2) {
        listOf("foo")
    } else {
        listOf("bar")
    }.map { 2 }
    println(test)
    It seems we don’t need to use safe null on the
    map
    call. However, if we remove the middle branch, then we do need it:
    var check1 = true
    var check2 = false
    val test = if (check1) {
        null
    } else {
        listOf("bar")
    }?.map { 2 }
    println(test)
    In both cases (without the
    map
    ), the type of
    test
    is
    List<String>?
    s
    e
    • 3
    • 10
  • s

    Susmitha Gudapati

    05/30/2022, 1:16 PM
    Hi, I have a typescript application. I want to create a Kotlin based application basing the same ts contracts/states. So I’ve started converting them from typescript to kotlin using custom scripts. While doing so, I’m facing a few challenges and one of them is to identity the kotlin’s equivalent implementation of typescript’s optional property, which is denoted by
    ?
    in states. For example: My contract in ts is -
    export interface A {
        id: number,
        name: string,
        imageId?: number,
        modified?: string,
    }
    In the interface A, the imageId and modified properties are optional. How do we denote the same functionality in kotlin’s classes?
    u
    r
    • 3
    • 5
  • f

    frogger

    05/31/2022, 6:08 AM
    Can I deprecate or warn if a
    fun
    in used in kotlin but issue no warning in java? We created a “bridge function” for java which should be avoided in kotlin code. I thought it would be nice to show a warning if used accidentally in kotlin code.
    r
    e
    y
    • 4
    • 5
  • m

    Michael de Kaste

    05/31/2022, 1:52 PM
    is it possible to generate compiler warnings when violating requirements? e.g.
    value class Example(val value: UInt){
    		init{
    			require(waarde <= 999_999_999u)
    		}
    	}
    obviously this doesn't work, but a range check on numbers seems trivial when you actually call constructors
    t
    p
    • 3
    • 2
  • e

    elect

    05/31/2022, 3:40 PM
    has anyone found a way to force mandatory parameters in DSL other than moving them as constructor arguments?
    j
    d
    • 3
    • 8
  • a

    Ayfri

    06/01/2022, 10:51 AM
    Hi, in which cases should I use arrays instead of lists ?
    e
    r
    +2
    • 5
    • 14
  • a

    Alejo

    06/02/2022, 10:22 AM
    Hi everyone! I want to initialize a
    Boolean
    variable from another one of type
    Boolean?
    and if the value is
    null
    then I will want to check if a value is present in another list and use that value for the initialization. Here is the code:
    val statuses = listOf("pending", "on-hold", "auto-draft") 
       val status = "pending"
       val isEditable: Boolean? = true
       
       val result = isEditable ?: status in statuses
       print(result)
    But this initialization using the Elvis operator always returns
    false
    , if I move the
    status in statuses
    to a different variable or I wrap it in a
    run {status in statuses}
    then the code works as expected. Am I missing something here or this is a bug? You can test the example here: https://pl.kotl.in/4QDgoNvYi
    m
    j
    • 3
    • 5
  • e

    Ellen Spertus

    06/02/2022, 8:55 PM
    Can you define methods directly in data classes, or do you define them in the same file as extension methods? I tried Googling this but couldn’t find a definitive answer.
    r
    c
    m
    • 4
    • 16
Powered by Linen
Title
e

Ellen Spertus

06/02/2022, 8:55 PM
Can you define methods directly in data classes, or do you define them in the same file as extension methods? I tried Googling this but couldn’t find a definitive answer.
r

Ruckus

06/02/2022, 9:01 PM
Why not try it? https://pl.kotl.in/8Hh3jLSiW
c

Cameron Mallory

06/02/2022, 9:02 PM
Hey there Ellen. You sure can!
data class Name(val first: String, val last: String){
    fun getFullName(): String =
        "$first $last"
}
If we run that in a Kotlin scratch file in Android Studio we get:
oops Ruckus beat me to it 🙂
r

Ruckus

06/02/2022, 9:03 PM
A scratch file is another great place to test
:plus1: 1
e

Ellen Spertus

06/02/2022, 9:04 PM
You all are right. I could have tested it. Let me ask a follow-up question: Should you define other methods in data classes.
c

Cameron Mallory

06/02/2022, 9:05 PM
That’ll prolly have a lot of opinions, but on my team we use them when needed.
🙏 1
Little old but here’s a discussion on reddit. I like the one comment that talks about separation of concerns, but also realizing sometimes it may make sense. https://www.reddit.com/r/Kotlin/comments/ehqe4e/why_is_it_bad_practice_to_have_functions_in_data/
in our codebase, a large majority are simple data classes, and usually if we need to do some simple “display to ui” or some such thing we’ll tend to put it in there vs an extension or transformer, etc.. ymmv of course
e

Ellen Spertus

06/02/2022, 9:11 PM
Are extension methods any better stylistically then defining the method within the data class?
Extension functions seem to violate separation of concerns just as much.
c

Cameron Mallory

06/02/2022, 9:13 PM
i’d prolly defer to what you or your team thinks feels better. I don’t think so tho really. iirc there’s no real overhead with extension methods for the most part
e

Ellen Spertus

06/02/2022, 9:15 PM
I’m doing an external code review in the absence of a Kotlin style guide and am trying to decide whether to say anything about the extension functions in the [same file as the] data class.
c

Cameron Mallory

06/02/2022, 9:18 PM
we have a couple of patterns in our codebase, the “newest” one being to have a
FooExts.kt
file that all extensions can go into for easy discoverability IF we think they’d be useful “globally”. Otherwise private extensions in the same file where it’s used works for us.
🙏 1
m

Matteo Mirk

07/04/2022, 3:30 PM
If the extensions are defined in the same file, then what’s the point of using them? In that case, to me it’s better just define those inside the data class. I mainly write extensions for: • 3rd party types I don’t control • my types but only localized in a certain point where that logic is cohesive with the rest, for example a conversion in a DAO or Port component
r

Ruckus

07/05/2022, 6:33 PM
If the extensions are defined in the same file, then what’s the point of using them?
This article gives a good explanation as to the point.
m

Matteo Mirk

07/06/2022, 2:19 PM
Thanks, read it, but still not convinced. Probably Roman’s example wasn’t good enough, but I still prefer my approach.
View count: 1