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

    Florian

    07/14/2019, 8:39 PM
    the comparison operators (>, < etc) can call directly to Java's own
    compareTo
    methods? They don't need Kotlin's
    Comparable
    interface?
    k
    d
    • 3
    • 16
  • k

    Katie Levy

    07/15/2019, 4:40 PM
    Checkout this webinar on how Kotlin is making our lives as engineers easier at Intuit: http://bit.ly/Kotlinwebinar
    :kotlin-flag: 2
    m
    • 2
    • 2
  • i

    Ive Vasiljevic

    07/16/2019, 1:59 PM
    I actually never got that message hence my question
    k
    k
    • 3
    • 5
  • f

    fangzhzh

    07/17/2019, 12:59 AM
    I'm been using kotlin for more than 3 years. I always use str?.let for null checking. I read a article today and I'm confused. Doesn't this recommendation really make sense?
    // NOT RECOMMENDED
    fun process(str: String?) {
        str?.let { /*Do something*/   }
    }
    
    // -> decompile will get
    public final void process(@Nullable String str) {
       if (str != null) {
          boolean var4 = false;
          /*Do something*/
       }
    }
    
    
    // RECOMMENDED
    fun process(str: String?) {
        if (str != null) {
            // Do Something
        }
    }
    e
    k
    +4
    • 7
    • 13
  • t

    tjohnn

    07/17/2019, 5:04 AM
    Is there a way to use `List`'s indexOf() of a list of a type on another type, for example I have a list of
    Product
    and
    ProductToOrder
    which are quite similar in terms of
    id
    and
    name
    , I overrode the`equals()` already but
    productsToOrder?.indexOf<Any>(product)
    always returns
    -1
    p
    • 2
    • 2
  • i

    Ive Vasiljevic

    07/17/2019, 9:48 AM
    Is it possible to have a default argument for a function parameter (function having another function as a parameter and that function parameter has a default value just as a variable could have)?
    o
    b
    • 3
    • 6
  • b

    Big Chungus

    07/17/2019, 12:42 PM
    Or you could use this:
    inline fun <T> Array<Array<T>>.forEach2D(action: (T) -> Unit): Unit {
        for (array in this) for (element in array) action(element)
    }
    f
    a
    • 3
    • 6
  • d

    Dennis Schröder

    07/17/2019, 3:29 PM
    Hey folks...is it possible to get all instances of a class (
    TimerTask
    ) at runtime and excute the
    run()
    method on them?
    a
    n
    +3
    • 6
    • 7
  • k

    Karolis

    07/18/2019, 3:25 PM
    So the answer is
    no
    ?
    val x = BigDecimal.ONE
    val y = x.setScale(999)
    
    x == y // => false
    x.compareTo(y) == 0 // => true
    b
    p
    +3
    • 6
    • 13
  • u

    ursus

    07/18/2019, 5:38 PM
    I may by blind but I dont see it, or should I just use
    map
    with identity function?
    k
    • 2
    • 2
  • f

    Florian

    07/19/2019, 4:01 PM
    but a for-loop is not an expression, right?
    k
    d
    h
    • 4
    • 7
  • m

    Mike R

    07/20/2019, 10:10 PM
    So I'm a bit confused about generics. I have an interface like this:
    interface IterableResponse {
    
        val data: List<T>
        val paginationInfo: More?
    }
    and I am getting an error "Unresolved reference T". I would like for any class that implements the interface to have a
    data
    property that is a list of anything - but I don't want to use
    List<Any>
    because I need the implementing classes to have typed Lists. Am I using generics incorrectly? What am I doing wrong?
    k
    h
    • 3
    • 4
  • a

    Akhil Suseelan

    07/22/2019, 10:16 AM
    Hi, I've two data class as follows: data class Resource( val location : String, val address: String ) data class Student( val id : Int, var userName : String, var screenName : String, var email : String, var place : Resource, var register : Instant, val timezone : TimeZone ) How to add some sample data to 'Resource' ?
    t
    k
    • 3
    • 2
  • m

    Marko Mitic

    07/22/2019, 11:42 AM
    Would this work?
    private fun <E> Set<E>.immutable(): Set<E> = if (this is MutableSet) this.toSet() else this
    k
    d
    +2
    • 5
    • 7
  • f

    Florian

    07/22/2019, 1:10 PM
    Is a for-loop the only place where
    in
    resolves to a call to the
    iterator
    ?
    k
    • 2
    • 2
  • f

    Florian

    07/22/2019, 1:12 PM
    also, does a for-loop get turned into a while loop under the hood?
    k
    • 2
    • 2
  • m

    Marko Mitic

    07/22/2019, 3:40 PM
    Are there some property delegates for computing something expensive, preferably using suspending fun?
    m
    c
    • 3
    • 5
  • s

    Stefan

    07/24/2019, 7:59 AM
    Hi. I'm having some problems with using listpreference.setValue or setIndexValue. None of the methods that I need to alter the values of a listpreference programmatically doesn't seem to be available. My class extends Preferencefragmentcompat Thanks Stefan
    :android: 2
    t
    r
    • 3
    • 8
  • s

    Soren Valle

    07/25/2019, 6:33 PM
    I'm stuck. Applying "kotlin-dce-js" to a js project is kicking "error: duplicate target file will be created for..." on build. Google has yielded little answers. It seems as though it's trying to output two files with the same name from the node_modules to the same dir. I have failed to locate information on how or if I should configure the scope of what is processes beyond https://kotlinlang.org/docs/reference/javascript-dce.html#configuring. Any help would be appreciated.
    k
    • 2
    • 2
  • m

    Mike R

    07/27/2019, 5:06 PM
    Why when extending a type would I lose properties on it? This is my code:
    fun Response<*>.createError(): Error {
        val errorBody = this.errorBody() ?: run {
            logger.error { "createError failed: null errorBody found" }
            throw ClassCastException("Null errorBody found on response")
        }
    
        val error = Gson().fromJson(errorBody.string(), models.Error::class.java)
        return error
    }
    What is happening is I am losing the contents of
    errorBody
    when I try to use the receiver (Response)... I've read over the docs on class extension and I don't see anything about this?
    m
    i
    • 3
    • 23
  • j

    Jérémy Touati

    07/27/2019, 6:18 PM
    hello there, very new to Kotlin (as in, I've started today), and I'm trying to find the way to have a secondary constructor work out in the following scenario: consider a chess board position that can be represented either through (x, y) coordinates (as a multidimensional array would), or as a string such as "B4"
    class Position(val x: Int, val y: Int) {
    	constructor(positionCode: String) {
    		// construct a position from code here
    	}
    }
    this yields an error as the secondary constructor must call the primary one with
    : this(...)
    i don't see an easy way to achieve this, i could call a function in the parent call such as
    this(getCoordsFromCode(positionFromCode))
    but it obviously won't work as the primary one expects two ints, and I don't think you can unpack an array into a function that isn't expecting vararg i could obviously swap the constructors and have the parent constructor call be something like
    this(getCodeFromCoords(x, y))
    , but I was wondering if I was missing something (and I'm pretty sure I am)
    m
    a
    • 3
    • 19
  • m

    Magnus W

    07/28/2019, 2:22 PM
    Hello! I'm also starting out with Kotlin (and Android). Is there a nicer (more idiomatic) way of doing the following check than the following?
    Untitled
    a
    • 2
    • 35
  • p

    Pablichjenkov

    07/28/2019, 9:50 PM
    Good talk. I wonder how the suspended send function waits until the Queue has more capacity to send. Or in other words how the send coroutine is informed that the Queue has capacity available. It is usual and dangerous in Java to synchronize on a queue monitor and wait for its size to change. Then whatever consuming thread that acquires the monitor will consume some items release the monitor and notify other waiters. I guess that in coroutines, above mechanics is not used, it probably works by re-scheduling another
    suspend send
    coroutine in the executor. Maybe not, maybe it spins lock on the Queue capacity. The same for the counterpart
    suspend consumer
    Does anyone can explain what happens internally?
    r
    • 2
    • 3
  • m

    Mike R

    07/28/2019, 11:35 PM
    is it possible to change the parameter name when using
    with(...) { }
    ? It was error-free until I changed it to
    with(...) { sf -> ... }
    and now IntelliJ says
    Expected no parameters
    m
    d
    m
    • 4
    • 7
  • d

    diego-gomez-olvera

    07/29/2019, 9:59 AM
    https://kotlinlang.slack.com/archives/C0DPADMT3/p1564394274000600
    m
    • 2
    • 4
  • s

    Sandeep Gurram

    07/30/2019, 7:20 AM
    Hi all, am an android developer. I want to learn server side programming, can any one suggest me where can i start ? I know nothing about server side programming.
    t
    p
    • 3
    • 2
  • d

    diego-gomez-olvera

    07/30/2019, 9:23 AM
    I am encouraging my colleagues to use Kotlin, and to do Kotlin Koans. While in some cases it is fine, in some others I find some pushback asking for how long will Koans completion take. Is there some kind of ‘official’ estimation or someone could share how long it took for them to do?
    t
    a
    • 3
    • 9
  • w

    w_bianrytree

    07/31/2019, 3:59 AM
    Hey guys. For class delegation. Can I delegate it to a property instead of value sent from constructor ? For example instead of:
    class Derived(b: Base) : Base by b {
        override fun printMessage() { print("abc") }
    }
    I want
    class Derived : Base by b {
        late init var b:Base
        fun initB(outerB:Base){
           b = outerB
        }
        override fun printMessage() { print("abc") }
    }
    Is it doable?
    🇳🇴 1
    d
    • 2
    • 1
  • b

    Bill Burcham

    07/31/2019, 2:48 PM
    I am trying to implement a trivial two-state state machine (turnstile) using `fun`s to implement states. First problem was that
    typealias
    didn’t support a recursive definition so I couldn’t do:
    typealias State = (pushes: ReceiveChannel<Unit>, coins: ReceiveChannel<Unit>) -> State
    So I had to resort to defining
    State
    as a
    @FunctionalInterface
    meh. With some liberal casts, this compiles but it fails at runtime (see comment above line 59): https://gist.github.com/Bill/b9cbfdb1d6fbba42258ee0a6fcee7240 Eschewing
    fun
    and defining the states as `object`s works but that seems like a lot of extra ceremony: https://gist.github.com/Bill/d5fa8c0290e49fccb90936745b29e86f Any ideas here?
    d
    • 2
    • 7
  • g

    Greg Stepniewski

    07/31/2019, 8:06 PM
    Is there a way to do this without using mutableList?
    fun Example.sequence(vararg operations: Example.() -> Example): List<Example> {
        val sequence = mutableListOf(this)
        operations.forEach { sequence.add(it(sequence.last())) }
        return sequence.toList()
    }
    s
    k
    +4
    • 7
    • 25
Powered by Linen
Title
g

Greg Stepniewski

07/31/2019, 8:06 PM
Is there a way to do this without using mutableList?
fun Example.sequence(vararg operations: Example.() -> Example): List<Example> {
    val sequence = mutableListOf(this)
    operations.forEach { sequence.add(it(sequence.last())) }
    return sequence.toList()
}
s

Shawn

07/31/2019, 8:08 PM
hmm, first thought is
foldWithNext
but that might not quite be what you want
g

Greg Stepniewski

07/31/2019, 8:14 PM
I don't think so. An example usage of this, assuming Example is Int would be:
5.sequence({plus(1)}, {minus(2)}, {times(2)}) // [5, 6, 4, 8]
key here is that I need to provide a list of different operations, and each operation builds on the result of the previous one
s

Shawn

07/31/2019, 8:18 PM
you’ll probably figure this out soon but I’ll take a stab at it later if there isn’t a solution posted
k

karelpeeters

07/31/2019, 8:23 PM
Really ugly solution, might give someone a better idea:
fun <T> T.chainOperations(ops: List<(T) -> T>): List<T> {
    var curr = this
    return listOf(curr) + ops.map { it(curr).also { curr = it } }
}
d

Dominaezzz

07/31/2019, 8:25 PM
Unfortunately yield twice but,
sequence {
    var curr = this
    for (op in operation) {
        yield(curr)
        curr = op(curr)
    }
    yield(curr)
}.toList()
m

Matias Reparaz

07/31/2019, 8:27 PM
fun Example.sequence(vararg operations: Example.() -> Example): List<Example> {
    return operations.fold(listOf(this)) {acc, cur -> acc + (cur(acc.last()))}
}
k

karelpeeters

07/31/2019, 8:28 PM
Looks like this variant of
fold
is called
scan
in other languages.
💯 1
👍 1
@Matias Reparaz The problem with folds like that is the terrible performance, it's unfortunate 😞
g

Greg Stepniewski

07/31/2019, 8:30 PM
@Matias Reparaz I don't think we can get cleaner than what you've done. This is perfect and I thank you 🙂
🤨 2
👍 1
m

Matias Reparaz

07/31/2019, 8:37 PM
I have my doubts about the performance... but if @Greg Stepniewski is looking for a clear implementation I think that my solution can be a good one
d

Dominaezzz

07/31/2019, 8:39 PM
operations.fold(mutableListOf(this)) { acc, cur -> acc += cur(acc.last()) }
might perform a bit better.
k

karelpeeters

07/31/2019, 8:40 PM
You need to actually return something from the lambda though.
d

Dominaezzz

07/31/2019, 8:40 PM
Although, it's still side effecty.
Ah I see.
m

marstran

08/01/2019, 8:05 AM
What about something like this:
fun Example.sequence(vararg operations: Example.() -> Example): List<Example> {
    if (operations.isEmpty()) {
        return listOf(this)
    }
    
    val mappedExample = operations.first()(this)
   
    val nextOperations = operations.drop(1)
    val seq = mappedExample.sequence(*nextOperations.toTypedArray())
    return listOf(this) + seq
}
It could probably be optimized to not create so many intermediate arrays and lists though. It should also probably be made tail recursive.
k

karelpeeters

08/01/2019, 9:21 AM
Remove the vararg, then you can skip the array and do
subList(1)
instead of
drop(1)
. Still terrible performance of course 🙃
d

Dico

08/01/2019, 6:25 PM
tailrec fun <E> E.sequence(ops: List<(E) -> E>, target: MutableList<E> = arrayListOf(), ind: Int = 0): List<E> {
    target += this
    if (ind >= ops.size) return target
    return ops[ind](this).sequence(ops, target, ind+1)
Seems pretty optimal to me
You could replace ops with vararg array
If you want to do it better you can make the function private and delegate to it with the default parameters
k

karelpeeters

08/01/2019, 6:28 PM
Also you can create an arraylist with the correct initial size.
d

Dico

08/01/2019, 6:29 PM
That's a good idea but we're reaching premature optimization territory
k

karelpeeters

08/01/2019, 6:29 PM
Maybe, but if it doesn't cost any effort 🙂
View count: 3