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

    Karlo Lozovina

    03/30/2021, 1:23 PM
    How to call a function defined inside a companion object, if I can only get to the companion object by reflection, so:
    SomeClass::class.companionObjectInstance
    y
    t
    • 3
    • 7
  • t

    Tomasz Krakowiak

    03/30/2021, 6:09 PM
    IDK, maybe I have a brain freez, but I can't figure out how to model it without lower bounds. (The apply method, that takes list and returns new list with modifications applied)
    interface ListModification<out E> {
    	fun applyTo(target: MutableList<in E>)
    	fun <T> apply(target: List<T>) : List<T>
    			where E : T
    }
    n
    n
    • 3
    • 38
  • d

    Dominick

    03/31/2021, 4:01 AM
    val commands: MutableSet<Command<JDACommandSender>> = mutableSetOf()
    get() = Collections.unmodifiableSet(field)
    My goal is to allow the class itself to modify
    commands
    directly, but others to only be able to get an unmodifiable version of the contents. Is there any direct way to achieve this?
    n
    • 2
    • 8
  • m

    Marko Novakovic

    03/31/2021, 7:24 AM
    recently I came across this article -> https://medium.com/google-developer-experts/companion-objects-kotlins-most-unassuming-power-feature-fb5c0451fbd0 It showcases some great use-cases but it made me a bit confused For example, what really is the difference between
    fun interface Validation : (String) -> Boolean {
        companion object
    }
    
    val Validation.Companion.validateEmail
        get() = Validation { it.isNotEmpty() }
    
    val Validation.Companion.validatePassword
        get() = Validation { it.isNotEmpty() }
    
    val isFormValid = Validation.validateEmail("email") && Validation.validatePassword("password")
    and
    typealias Validation = (String) -> Boolean
    
    val validateEmail: Validation = { email: String -> email.isNotEmpty() }
    val validatePassword: Validation = { password: String -> password.isNotEmpty() }
    
    val isFormValid = validateEmail("email") && validatePassword("password")
    What are use-cases where first one would add value over second one? Or is this just semantic difference?
    t
    • 2
    • 9
  • a

    Andrew Ebling

    03/31/2021, 8:54 AM
    what’s the cleanest/most kotlin-idiomatic way to define a method which can take one of 3 types of object, short of declaring 4x separate methods? The types in question are Date, String, Bool and Int. Wondered about a
    sealed class
    unsure if this is the most appropriate approach.
    b
    t
    +3
    • 6
    • 9
  • d

    dreamreal

    03/31/2021, 1:34 PM
    oh no, april 1 is coming
    😰 3
    p
    d
    c
    • 4
    • 4
  • u

    user

    03/31/2021, 3:50 PM
    message has been deleted
    r
    • 1
    • 1
  • s

    Sami Eljabali

    03/31/2021, 11:00 PM
    Hello, I’m trying to create a utility class that’s Java compatible. I was able in the past to do the following:
    Intents.kt
    @file:JvmName("IntentsUtil")
    @file:JvmMultifileClass
    
    open class Intents {
        companion object
    }
    PlayStoreIntents.kt
    @file:JvmName("IntentsUtil")
    @file:JvmMultifileClass
    
    fun Intents.Companion.viewAppOnPlayStore(appUri: String): Intent =
        Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(appUri)
            setPackage(Apps.PLAY_STORE.url)
        }
    When invoked Java side was able to simply:
    IntentsUtil.viewAppOnPlayStore("foo");
    Now however, it requires me to do:
    IntentsUtil.viewAppOnPlayStore(Intents.Companion, "foo");
    Any idea to why that is? How can I avoid passing the Companion object?
    n
    r
    a
    • 4
    • 15
  • c

    Coen

    04/01/2021, 8:27 AM
    Hi, im looking at detekt configuration. Is there any popular detekt config next to the default one like there is with PMD etc? Or to the people here using detekt, what configuration are you using?
    w
    • 2
    • 4
  • g

    Gilles Barbier

    04/01/2021, 4:01 PM
    Hi, what's the most efficient way to remove an element from a mutable set of ByteArray??
    val b = "1".toByteArray()  
    val s = mutableSetOf("1".toByteArray())
        
    s.remove(b) // <== this does not work, probably because "1".toByteArray() != "1".toByteArray()
    
    s.removeIf { b.contentEquals(it) } // <= this works
    r
    t
    n
    • 4
    • 51
  • r

    Rob Elliot

    04/01/2021, 7:07 PM
    Just found myself writing these…
    fun Runnable.toFun(): () -> Unit = { this.run() }
    fun Function0<Unit>.toRunnable(): Runnable = Runnable { this() }
    
    fun <T> Callable<T>.toFun(): () -> T = { this.call() }
    fun <T> Function0<T>.toCallable(): Callable<T> = Callable { this() }
    and then wondered a) do they already exist or b) is there a better way?
    s
    n
    n
    • 4
    • 21
  • k

    Karlo Lozovina

    04/02/2021, 8:57 AM
    Are there any plans to support module-wide sealed classes?
    👍 1
    m
    d
    • 3
    • 6
  • s

    Slackbot

    04/02/2021, 5:53 PM
    This message was deleted.
    d
    • 2
    • 1
  • e

    elect

    04/02/2021, 11:29 PM
    is
    ${'\n'}
    the only way to add a new line in triple quotes?
    b
    p
    • 3
    • 5
  • a

    Andre Stefanov

    04/03/2021, 7:33 PM
    hi everyone. i am building a project with tornadofx (javafx kotlin) and opencv (native libraries with optional java wrappers). The application should later run on windows, macos and linux. At the moment i struggle to include the native libraries into my kotlin multiplatform project (gradle kotlin) and googling is unfortunatelly pretty hard because most examples are for android and ndk ... which is not what i am using. Is there an example how to include native libraries in kotlin multiplatform projects or maybe even include OpenCV as a CMake based module?
    c
    • 2
    • 4
  • s

    Slackbot

    04/04/2021, 4:08 AM
    This message was deleted.
    n
    t
    • 3
    • 23
  • c

    christophsturm

    04/04/2021, 5:11 PM
    are there any plans to make user friendly compiler error message a priority for kotlin like for example elm, rust or scala have done? https://www.scala-lang.org/blog/2016/10/14/dotty-errors.html https://elm-lang.org/news/compiler-errors-for-humans https://blog.rust-lang.org/2016/08/10/Shape-of-errors-to-come.html
    👍 4
    o
    a
    l
    • 4
    • 26
  • p

    Peter

    04/04/2021, 8:46 PM
    trying to use reflection in 1.5.0-M2 and somehow the get doesn't compile since it expects object of type Nothing and not Transaction:
    fun getProperties(t: Transaction) {
        t::class.memberProperties.forEach {
                println(it.name)
                println(it.get(t)) // gives error since it doesn't expect type Transaction 
        }
    }
    y
    a
    • 3
    • 7
  • n

    Nikhil

    04/05/2021, 11:17 AM
    What's the difference between Retrofit and okHttp?
    :not-kotlin: 4
    :google: 4
    c
    c
    +2
    • 5
    • 7
  • f

    Fernando Avanzo

    04/05/2021, 2:49 PM
    hi folks, my name is Fernando Avanzo, and i work with kotlin above two year, all what i learned is throught study of the documentation Jetbrains , webninars, and of the comunnity tutorials in Medium. I would like to ask, if have a offcial program of certification of koylin? how the OCJP by Oracle? If has, what i need do to get? Thanks for the help guys
    b
    a
    f
    • 4
    • 4
  • v

    v79

    04/05/2021, 2:51 PM
    Does anyone else find trailing lambdas confusing? Especially when learning, I wish I could tell IntelliJ to reformat all code to be explicit about trailing lambdas - it would really help me to understand what is actually going on. Or perhaps a different block delimitator could have been chosen, besides { }, to make it clearer. Or maybe it's just me!
    🇳🇴 2
    b
    m
    • 3
    • 8
  • h

    hisham bin awiad

    04/05/2021, 2:51 PM
    Are there any tools to "visualize" your code line by line?
    b
    v
    m
    • 4
    • 5
  • n

    nkiesel

    04/05/2021, 5:11 PM
    We (still) use slf4j/logback in our Kotlin code. Currently, we define a
    val logger: Logger = LoggerFactory.getLogger(Foo::class.java)
    in the companion object of a class
    Foo
    . I remember a discussion about defining this as a class property instead of as a companion object property (which would then allow to use
    val logger: Logger = LoggerFactory.getLogger(this::class.java)
    ) but I can't find it anymore. What is current best practice here ?
    n
    a
    +3
    • 6
    • 61
  • n

    nkiesel

    04/05/2021, 6:01 PM
    slightly connected Q: the return type of a Java method
    getFoo
    which returns an object of type
    Foo
    (and never returns
    null
    ) is
    Foo!
    . Should I (a) ignore this and use
    val foo = getFoo()
    (b) use
    val foo: Foo = getFoo()
    or (c)
    val foo = getFoo()!!
    🅱️ 6
    n
    c
    +2
    • 5
    • 24
  • s

    Sandeep Chandra

    04/06/2021, 9:22 AM
    I have just started looking at Kotlin, I have been using F# on .NET for a while now and I am liking Kotlin. I am missing pipe operator in Kotlin though, is there any plan to bring the pipe operator to Kotlin?
    m
    g
    e
    • 4
    • 5
  • s

    Sandeep Chandra

    04/06/2021, 9:23 AM
    The other question I have is with regards to Exposed, is there any tool to generate structures for existing database?
    c
    p
    • 3
    • 2
  • t

    thhh

    04/06/2021, 1:07 PM
    Hi, is there a beginner channel to ask questions related to the logic in the code? The code is related to if else and recursive.
    c
    • 2
    • 2
  • c

    Cody Mikol

    04/06/2021, 8:12 PM
    Is there some way to make kotlin assume that any values coming from a java method or class are nullable?
    c
    n
    e
    • 4
    • 3
  • y

    Yuri Drigin

    04/07/2021, 8:54 AM
    I got this error
    java.lang.AssertionError: Enum class does not have .values() function
    when make enum
    Serializable
    Kotlin 1.4.31 Canary 13 Custom Serializer for this enum doesn’t help, (((
    👀 1
    a
    • 2
    • 2
  • d

    dave08

    04/07/2021, 9:11 AM
    Given a mutable list of:
    data class Foo(val id: Int, val name: String)
    What's an ideomatic way of searching for an
    id
    and replacing in-place the entry with another name (without turning the list into a map)? And return the id or the found entry as a bonus..
    b
    a
    e
    • 4
    • 26
Powered by Linen
Title
d

dave08

04/07/2021, 9:11 AM
Given a mutable list of:
data class Foo(val id: Int, val name: String)
What's an ideomatic way of searching for an
id
and replacing in-place the entry with another name (without turning the list into a map)? And return the id or the found entry as a bonus..
b

Big Chungus

04/07/2021, 9:14 AM
You can't replace the name as it's immutable. Or do you mean replacing entire element with a modified copy if it?
d

dave08

04/07/2021, 9:15 AM
yes
a

arekolek

04/07/2021, 9:15 AM
• do you want to replace it in-place or is it ok to remove the item and add the new one to the end of the list? • do you want to replace only first or all occurrences?
d

dave08

04/07/2021, 9:15 AM
Only the first, and better in-place.
b

Big Chungus

04/07/2021, 9:16 AM
Seems like some kind of pop operator would help here then. Or if you're happy with replacing all occurences, you can use map operator
d

dave08

04/07/2021, 9:17 AM
map? That would just recreate the whole list, whereas now I have a mutable one...
a

arekolek

04/07/2021, 9:18 AM
And return the id or the found entry as a bonus
did you mean the old
name
maybe? why return
id
if it's going to be the same as the passed argument or null (if not found)?
d

dave08

04/07/2021, 9:18 AM
In my case, I search on another field in the data class... I guess the contrived example is a bit too contrived 😅
a

arekolek

04/07/2021, 9:20 AM
ok, I read "or found entry" as "of found entry", but returning the entry makes sense
d

dave08

04/07/2021, 9:22 AM
-- found entry is also fine... I could get the id from there I need this to create db repository stubs for unit testing... I thought it would be easier to simulate INSERT ... ON CONFLICT ... RETURNING id ... it just turned out not being such a one liner anymore...
a

arekolek

04/07/2021, 9:25 AM
I came up with this:
fun MutableList<Foo>.replace(id: Int, name: String): Foo? {
    val index = indexOfFirst { it.id == id }
    return if (index > -1) {
        set(index, get(index).copy(name = name))
    } else {
        null
    }
}
➕ 1
d

dave08

04/07/2021, 9:27 AM
Thanks! If I turn that into a more generic function, it should come in handy 🙂, I wonder if this (in some form) could be an interesting addition to the stdlib? There's already a replaceAll...
a

arekolek

04/07/2021, 9:34 AM
Maybe 🤔
fun <T> MutableList<T>.replace(predicate: (T) -> Boolean, transformation: (T) -> T): T? {
    val index = indexOfFirst(predicate)
    return if (index > -1) {
        set(index, transformation(get(index)))
    } else {
        null
    }
}

fun MutableList<Foo>.replace(id: Int, name: String): Foo? {
    return replace({ it.id == id }) { it.copy(name = name) }
}
👍 1
👍🏼 1
b

Big Chungus

04/07/2021, 9:37 AM
I'd also make it inline
👍🏼 1
👍 1
d

dave08

04/07/2021, 9:38 AM
I did the same, but I used a receiver for the predicate... but I think I like yours better... since I think all the stdlib functions do that. Inline to save all the lambdas, I suppose. That's also an idea!
b

Big Chungus

04/07/2021, 9:41 AM
Even better yet, crossinline lambda args too
a

arekolek

04/07/2021, 9:49 AM
Even better yet, crossinline lambda args too
does that change anything in the case above?
b

Big Chungus

04/07/2021, 9:51 AM
It'll not allocate lambda args and instead just unfurl them in call sites, so you end up with code that only uses stdlib
Basically erasing the existence of your helper fun in bytecode alltogether
a

arekolek

04/07/2021, 10:52 AM
isn't it what
inline
does? bytecode seems to be exactly the same with and without
crossinline
e

ephemient

04/07/2021, 3:56 PM
don't use crossinline unless you need it, it prevents nonlocal returns
you can consider using https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-mutable-list/list-iterator.html to mutate a list entry in place instead of relying on indices
e.g.
Untitled.kt
➕ 1
a

arekolek

04/07/2021, 7:14 PM
I think the above needs some slight modification to return the value before transformation, rather than after transformation
e

ephemient

04/07/2021, 7:50 PM
I misread the previous code. behavior now matches
👍 1
👍🏼 1
d

dave08

04/08/2021, 10:00 AM
Thanks! I also ended up making this one (also pretty handy for stubbing repositories in tests):
fun <T> MutableList<T>.modify(predicate: (T) -> Boolean, transformation: T.() -> Unit): T? {
        val iterator = listIterator()
        while (iterator.hasNext()) {
            val value = iterator.next()
            if (predicate(value)) return value.also { value.transformation() }
        }
        return null
    }
View count: 13