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

    moizest89

    04/26/2019, 3:49 PM
    Hi!! I’ve tried to implement a Builder pattern design in Kotlin but on internet find a different ways to do. Does anyone have an idea the best way to implement one? 😬 Thanks!!!
    t
    c
    +2
    8 replies · 5 participants
  • a

    Anton Lakotka [JB]

    04/26/2019, 7:30 PM
    Hi, I want to execute N tasks in a pool of K coroutines. How can I do that? I mean:
    val todos = (0..1000000).map { payload -> someTaskBuilder(payload) }
    // On runtime JVM will try to execute as much as it can at the same time.
    val results = todos.map { task -> async { task() } }.awaitAll()
    // But I want to confine total amount of running coroutines here.
    // Something like this:
    coroutineScope ( someContextWithCoroutinesLimit ) {
       /* todos execution */
    }
    Maybe I want something strange. The reason why I want that is an external system which does some work during task execution. And that external system has Connection Limit. I could fix that by using some Pool. But I was wondering is it possible to limit somehow coroutines amount in easy way.
    p
    1 reply · 2 participants
  • e

    elect

    04/26/2019, 7:46 PM
    I need a structure <K, V> where I can easily retrieve either the V given K as usually and viceversa. I used a
    MutableMap
    till now, but it's quite ugly to extract the K given the V (I can loop on the whole
    entries
    and get the first match). Is there anything better for my case?
    s
    d
    +1
    6 replies · 4 participants
  • d

    Demetrious Robinson

    04/26/2019, 9:59 PM
    Quick question.. I am new to Kotlin and I am wondering can anyone tell me the use of the componentN function in data classes? For example
    data class Person(val firstName: String ="Demetrious", val lastName:String = "Robinson")
    val person1 = Person()
    println(person1.component1()) // "Demetrious"
    I don't see the use of that as it only returns the value and not the property name. Wouldn't it be simpler to just write
    println(person1.firstName)
    c
    l
    3 replies · 3 participants
  • a

    Andrew Gazelka

    04/27/2019, 6:35 PM
    /**
     * Infinite loop that reads this atomic variable and performs the specified [action] on its value.
     */
    public inline fun <T> AtomicRef<T>.loop(action: (T) -> Unit): Nothing {
        while (true) {
            action(value)
        }
    }
    ummm I am confused... why would anyone use this? Why not just
    AtomicRef#value
    ? (in regards to https://github.com/Kotlin/kotlinx.coroutines/blob/69c26dfbcefc24c66aadc586f9b5129894516bee/kotlinx-coroutines-core/common/src/sync/Mutex.kt#L146-L155)
    1 reply · 1 participant
  • m

    mvbrenes

    04/28/2019, 4:03 AM
    out of curiosity i’ve started peeking into the kotlin byte code again. This time though ive been noticing some off behavior when decompiled back to java. Notice the random boolean declarations that are not used, these are littered throughout, anyone have any insight their use may be?
    @NotNull
       public final List makeCachedVendorList(@Nullable Integer size) {
          int var2 = size != null ? size : TestDataFactory.INSTANCE.randomInt(1, 15);
          boolean var3 = false;
          boolean var4 = false;
          ArrayList var5 = new ArrayList(var2);
          boolean var6 = false;
          boolean var7 = false;
          int var15 = 0;
    
          for(int var8 = var2; var15 < var8; ++var15) {
             boolean var10 = false;
             int var12 = false;
             CachedVendor var14 = makeCachedVendor$default(INSTANCE, 0, 1, (Object)null);
             var5.add(var14);
          }
    
          return (List)var5;
       }
    e
    i
    4 replies · 3 participants
  • c

    crummy

    04/28/2019, 9:49 AM
    Is there a way to achieve the same thing, though? Overwrite the object we're attached to?
    k
    k
    3 replies · 3 participants
  • m

    Matthew Good

    04/28/2019, 2:59 PM
    is it possible to implement the specification pattern in kotlin? as i tried https://dzone.com/articles/java-using-specification but i get the following undefined references: Predicate CriteriaBuilder Root
    d
    p
    +1
    8 replies · 4 participants
  • m

    Matthew Good

    04/28/2019, 3:08 PM
    also does anyone know how to correctly accomplish combinators,
    combinator(val).and(val).and(val).and(val) ...
    as at this point the only thing i can think of is to implement it as a linked list but i already use the functions provided by the linked list implementation in
    combinator
    val i = input("1234") // i.value is set to "1234"
    val combinator = i.combinator("12")
    if (
        combinator.peek() // if "1234" starts with "12"
    ) {
        combinator.pop() // i.value is now "34" from "1234"
    }
    this is my current attempt at making such https://pl.kotl.in/1p-y2OEJA (using a binary tree or similar) which currently fails with
    n4 it.value = 1
    n4 it.value = 2
    n5 it.value = 1
    n5 it.value = 3
    instead of
    n4 it.value = 1
    n4 it.value = 2
    n5 it.value = 1
    n5 it.value = 2
    n5 it.value = 3
    for
    fun main() {
        val tree = Tree()
        val n1 = tree.Node(1)
        val n2 = tree.Node(2)
        val n3 = tree.Node(3)
        val n4 = n1.append(n2)
        val n5 = n4.append(n3)
    
        n1.forEach { println("n1 it.value = ${it.value}") }
        n2.forEach { println("n2 it.value = ${it.value}") }
        n3.forEach { println("n3 it.value = ${it.value}") }
        n4.forEach { println("n4 it.value = ${it.value}") }
        n5.forEach { println("n5 it.value = ${it.value}") }
    }
    p
    k
    8 replies · 3 participants
  • a

    Andrew Gazelka

    04/28/2019, 4:17 PM
    if I am ever taking in a
    List
    and expect the contents to be the same, I should create a copy, right? (since the
    List
    might also be Immutable) ... is there any good way to only copy if it is mutable or would that be too much of a micro-optimization?
    r
    r
    +2
    5 replies · 5 participants
  • m

    Matthew Good

    04/28/2019, 7:03 PM
    is it possible to have a list that accepts only X or Y type and not
    Any
    d
    r
    2 replies · 3 participants
  • a

    Allan Wang

    04/28/2019, 9:11 PM
    Is there an equivalent to a bytestream in kotlin? I see byte array, but the file I’m working with may be arbitrarily large. I’d like to be able to read data with different sizes (Reading a java class file, where values can be 2 bytes, 4 bytes, etc)
    n
    c
    2 replies · 3 participants
  • m

    max.denissov

    04/29/2019, 5:40 AM
    Hello! Who know, does exists slack channel special for kotlin-multiplatform ?
    g
    1 reply · 2 participants
  • y

    Yossi Saiada

    04/29/2019, 8:02 AM
    Hi, I want to get a binary representation of an object. The easier way I found was this one:
    val file = File("temp")
    ObjectOutputStream(FileOutputStream(file)).use { it.writeObject(obj) }
    return file.readBytes()
    However, I really want to avoid using files. So, I'm wondering whether there is a better/shorter way to achieve the same result. Thanks 🙂
    :google: 3
    d
    1 reply · 2 participants
  • m

    Matthew Good

    04/29/2019, 1:16 PM
    this would be a correct implementation of
    and
    and
    or
    right? (not including combinations and association, eg
    A and B or C
    >
    (A and B) or C
    or
    A and (B or C)
    )
    fun peek(): Boolean = if (list.size != 0) peekMultiple() else peekSingle()
    
    // private fun peekSingle omited
    
    private fun peekMultiple(): Boolean {
        val listTmp = cloneList(list).iterator()
        if (list.all { it.type == operatorAnd }) {
            var matches = 0
            val max = list.size
            while (listTmp.hasNext()) {
                val stackTmp = listTmp.next().once!!
                if (stackTmp.peek()) {
                    matches++
                    stackTmp.pop()
                } else break
            }
            if (matches == max) return true
            return false
        } else if (list.all { it.type == operatorOr }) {
            while (listTmp.hasNext()) if (listTmp.next().once!!.peek()) return true
            return false
        }
        else return false // unsupported operator or combination of different operators
    }
    
    infix fun and(right: IsSequenceOnce): IsSequenceOnce {
        val stackTmp = parent.clone().IsSequenceOnce(this.value)
        if (this.list.size != 0) stackTmp.list.addAll(this.list) else stackTmp.list.add(Types().also { it.add(this, operatorAnd) })
        if (right.list.size != 0) stackTmp.list.addAll(right.list) else stackTmp.list.add(Types().also { it.add(right, operatorAnd) })
        return stackTmp
    }
    
    infix fun or(right: IsSequenceOnce): IsSequenceOnce {
        val stackTmp = parent.clone().IsSequenceOnce(this.value)
        if (this.list.size != 0) stackTmp.list.addAll(this.list) else stackTmp.list.add(Types().also { it.add(this, operatorOr) })
        if (right.list.size != 0) stackTmp.list.addAll(right.list) else stackTmp.list.add(Types().also { it.add(right, operatorOr) })
        return stackTmp
    }
    for example,
    val E = parseStream.IsSequenceOnce("E")
        val F = parseStream.IsSequenceOnce("F")
        val FE = F or E
        val EF = E and F
        println(EF.peek())
        println(FE.peek())
    🤮 2
    😱 2
    s
    r
    +1
    27 replies · 4 participants
  • a

    arekolek

    04/29/2019, 2:06 PM
    By default yes https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/lazy.html#
    default thread-safety mode LazyThreadSafetyMode.SYNCHRONIZED.
    Locks are used to ensure that only a single thread can initialize the Lazy instance.
    p
    4 replies · 2 participants
  • b

    brian

    04/29/2019, 2:53 PM
    How do I use setAudioattribures instead of setAudioStreamtype
    :google: 4
    r
    1 reply · 2 participants
  • m

    Matthew Good

    04/29/2019, 4:29 PM
    is it possible to make
    val x: Stack<String> = "a"
    auto convert to
    return Stack("a")
    via some function without needing to explicitly state
    val x = Stack<String>("a")
    s
    k
    +1
    25 replies · 4 participants
  • s

    Slackbot

    04/29/2019, 5:17 PM
    This message was deleted.
    m
    k
    2 replies · 3 participants
  • m

    Matthew Good

    04/29/2019, 5:31 PM
    is it possible to have multiple
    infix
    functions in a chain? for example,
    true and not false
    where
    and
    and
    not
    are
    infix
    functions
    c
    g
    3 replies · 3 participants
  • s

    Stefan Peterson

    04/29/2019, 6:08 PM
    Is there a way to reference
    self
    or something equivalent in a constructor of a data class such that you could do something like:
    abstract class A(abstract name: String?)
    
    data class B(override val name: String? = self::class.simpleName): A()
    
    val b = B()
    print(b.name)        // B
    s
    b
    20 replies · 3 participants
  • m

    Matthew Good

    04/29/2019, 6:19 PM
    Untitled.md
    k
    3 replies · 2 participants
  • d

    Dangelomjoyce

    04/29/2019, 10:51 PM
    Good afternoon, I'm new to Kotlin and working through a Big Nerd Ranch book, I came across the function in their code and it isn't working, can someone help me with the solution.val healthStatus = when (healthpoints) { in 100..89 -> EXCELLENT_HEALTH in 90..99 -> GOOD_HEALTH in 75..98 -> MINOR_HEALTH in 75..89 -> if (isBlessed) {IS_BLESSED } else { } in 15..74 -> LOW_HEALTH else -> POOR_HEALTH } ... println("$name $healthStatus")isBlessed is set to true, and I have a string stored in const val IS_BLESSED. The issue I am having is that string is not printing regardless the range of the healthpoints.
    d
    i
    7 replies · 3 participants
  • r

    rook

    04/29/2019, 11:14 PM
    I’m trying to get model extensions defined on an interface to only be accessed via the implementations of the interface. Unfortunately, it looks like within lambdas being passed to the implementations, the context required to actually use the extensions is not fulfilled. Here is an example of what I’m trying to do: https://pl.kotl.in/byJT79Q0W A quick summary:
    interface Foo{
      fun createContext(action: MyObject.() -> Unit)
      fun MyObject.makeChange()
    }
    
    myObject.makeChange() //this should be illegal
    myFoo.createContext {
      makeChange() //this should be legal
    }
    Is there a way to achieve what I’m attempting?
    b
    2 replies · 2 participants
  • d

    Dangelomjoyce

    04/29/2019, 11:29 PM
    -.txt
    g
    4 replies · 2 participants
  • d

    Dangelomjoyce

    04/30/2019, 12:38 AM
    I suppose I am asking for further help understanding when expressions. In the above code snippet, not only does IS_BLESSED (line 40) not print, but "UNKNOWN RACE" in line 25 always prints. But if race is assigned to orc, and the when expression checks for race, why doesnt it print HILL_PEOPLE?
    g
    s
    6 replies · 3 participants
  • i

    iex

    04/30/2019, 12:37 PM
    is there a not so verbose way to define a class that contains all the fields from another + a new one (I don't care if it's via inheritance, composition)
    j
    s
    27 replies · 3 participants
  • i

    iex

    04/30/2019, 12:38 PM
    I'm modelling notification objects. The "default" ones, with name, description and so on, and then I have "progress" notifications which have everything contained in the "default" ones + a field for a message when the process is complete
    r
    3 replies · 2 participants
  • e

    elect

    04/30/2019, 12:54 PM
    working with generic numbers of type
    N : Number
    . If I have a comparison shall I cast
    if((v as Int) == (vCur as Int))
    or I can leave it plain
    if(v == vCur)
    ?
    r
    d
    11 replies · 3 participants
  • r

    Rohit Mohta

    04/30/2019, 1:40 PM
    Is there an example of passing system property to application via Gradle application.run using Kotlin DSL?
    g
    1 reply · 2 participants
Powered by Linen
Title
r

Rohit Mohta

04/30/2019, 1:40 PM
Is there an example of passing system property to application via Gradle application.run using Kotlin DSL?
g

gildor

05/02/2019, 1:45 AM
tasks.named("run") { //Your config }
View count: 1