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
getting-started
  • c

    CBedzz

    01/24/2020, 5:49 AM
    New to kotlin & android. I have a button and when it is clicked, I display a toast. I want to format the toast before I display it. I wanted to do something like Toast.makeText().setGravity().show() but setGravity doesn't return the toast to show, so it seems I can either define a toast variable to setup before I show it or for chaining, I could use .also{}. Just wondering if there are any pluses or minuses of each method or what is the "Kotlin way?" Thanks. Here is code for both ways I set it up.
    trueButton.setOnClickListener {
                val toast = Toast.makeText(
                    this,
                    R.string.correct_toast,
                    Toast.LENGTH_SHORT
                )
                toast.setGravity(<http://Gravity.TOP|Gravity.TOP>, 0 , 200)
                toast.show()
            }
    
            falseButton.setOnClickListener {
                Toast.makeText(
                    this,
                    R.string.incorrect_toast,
                    Toast.LENGTH_SHORT
                ).also {
                    it.setGravity(<http://Gravity.TOP|Gravity.TOP>, 0, 200)
                }.show()
            }
    i
    a
    +1
    5 replies · 4 participants
  • j

    Jakub Gwóźdź

    01/24/2020, 11:43 AM
    Hi. I have a working Kotlin 1.3.61 project, using gradle 6.0.1, nothing fancy, simple jvm/jdk11 build. I want to create a few utility scripts that could be used for tooling purposes, nothing that would go to production. (Usually I do it by creating some kotlin file with
    main()
    inside test source root) So I created the new
    script
    directory and a
    ...ws.kts
    file inside it, but here I have three issues: • the "use classpath of module:" toolbar menu is not present • script, when run, has working directory set to kotlin home, not project dir • although the build directory from project is present on classpath, the dependencies are not What am I doing wrong?
    m
    7 replies · 2 participants
  • c

    Chills

    01/26/2020, 11:27 AM
    Hi ! im new here how to setup kotlin in IntellJ IDE , have seen couple of video on youtube and read article but damn when ever i click the
    Run button
    it shows set configuration. Feel Intellj is really complex.
    d
    e
    +1
    12 replies · 4 participants
  • c

    Chills

    01/26/2020, 11:28 AM
    currently use kotlin for backend and not an app engineer so i dont understand most article on coroutines which target android folks.
    d
    2 replies · 2 participants
  • v

    Vadym

    01/26/2020, 1:19 PM
    Hello, I want to participate in a project to get some team working and someone else's code understanding skills as well as get more experience with programming, libraries and test automation. Please note that the only useful thing I've created is a simple internal tool for me and my colleagues, so I'm kinda very junior with some TornadoFX and Android SDK knowledge. If you know where I can find such a project or you have any advice for me - please, do not hesitate to reply. Thank you a lot and have a great day!
    m
    1 reply · 2 participants
  • o

    Obaid Jatoi

    01/28/2020, 10:17 AM
    Hello all, We want to start with Kotlin multiplatform, Can anyone please tell me that what is the scope of third party apps? I mean if there is any third party analytic SDK which currently we are using on native android and IOS, how we will accommodate these SDK'S with Kotlin multiplatform library or project you can say ?
    a
    2 replies · 2 participants
  • m

    Mark

    01/29/2020, 4:51 PM
    How to write a function reference (like
    someInstance::someFun
    ) but where the function has a receiver?
    s
    a
    +1
    5 replies · 4 participants
  • c

    cookiecookiecookie

    01/30/2020, 12:19 AM
    nope
    a
    14 replies · 2 participants
  • m

    Mark

    01/30/2020, 10:39 AM
    Say I have
    fun myCheck(): Boolean
    which I want to repeatedly call until it returns false. If I use
    while (myCheck()) {}
    then I get a warning saying “control flow with empty body”. So I guess
    while
    is supposed to be used with a non-empty body. Does this mean there is a more appropriate way?
    f
    e
    +3
    9 replies · 6 participants
  • c

    cookiecookiecookie

    02/03/2020, 12:29 AM
    so can you do like
    var m3 = mutableMapOf<String, Any
    d
    s
    +1
    7 replies · 4 participants
  • k

    Konstantin Petrukhnov

    02/04/2020, 8:12 AM
    Is there some better form than .toByte() for case below?
    val myVal: Byte
    ...
    if(myVal != 0.toByte()) {}
    t
    a
    3 replies · 3 participants
  • v

    vitaly

    02/04/2020, 6:28 PM
    Is there any way to create double or float range from String? I have strings like "0.1-0.5", "5.5-5.8", etc. in my configuration and I want to transform them to ClosedFloatRange/ClosedDoubleRange. I could create an extention function for String type but cannot instantiate those types as they are private. Also I wonder why integer ranges (IntRange,LongRange and so on) are public but floating point ranges are not.
    a
    2 replies · 2 participants
  • d

    Dawid Hyzy

    02/05/2020, 9:17 AM
    How do I bind value from JSON to ListView ? Here's sample of my JSON
    [{"kodenik":"2013129733","namakaryawan":"YASTI RIZKIA","kodebagian":"TRIE","tglupdate":"2019-12-09","tglabsen":"2019-12-09","jamin":"10:05","jamout":""},
    {"kodenik":"2015184941","namakaryawan":"AGUNG SUBEKTI","kodebagian":"TUOL","tglupdate":"2019-12-09","tglabsen":"2019-12-09","jamin":"17:03","jamout":""}]
    s
    3 replies · 2 participants
  • t

    Tuang

    02/05/2020, 2:50 PM
    I want to build a query string with coolest way
    val query = "INSERT INTO table (id, name, age) VALUES (?,?,?)"
    this is ordinary way (i usually use) and the problem is, the parameter `?`need to append according to the increase or decrease of column
    id, name, age
    so i tried,,,
    var column = "id, name, age"
    val query = "INSERT INTO table (${column}) VALUES (${(1..3).forEach { ? }})"
    the part
    ${(1..3).forEach { ? }}
    is incorrect, i don’t know how to do. hope you got me,
    a
    r
    +4
    9 replies · 7 participants
  • s

    Stefan Russo

    02/06/2020, 2:45 PM
    Does Kotlin have any built-in libraries for HTTP Requests similar to Java 11's built-in HTTPClient?
    d
    m
    +1
    5 replies · 4 participants
  • j

    J6ey

    02/09/2020, 12:49 PM
    The code should be exactly the same. Am I missing something?
    d
    m
    10 replies · 3 participants
  • d

    Dawid Hyzy

    02/10/2020, 1:15 AM
    I would like to ask regarding setter and getter, I have piece of code like that. Whenever I tried to access the variable listToko on another class, it always return empty string, while when I println resp, I know there's the value inside resp. Is there something wrong with how I use setter / getter ? Thanks
    d
    8 replies · 2 participants
  • a

    atsushi-koshikizawa

    02/10/2020, 4:03 AM
    Failed to run
    kotlinc
    . How do I fix it? (It may occur after updating OS X to 10.15.3.)
    Untitled
    s
    4 replies · 2 participants
  • d

    Dawid Hyzy

    02/11/2020, 6:44 AM
    Hi, I would like to ask, I have this kind of code below :
    var abc2 = client2.newCall(post2).enqueue(object: Callback {
                override fun onResponse(call: Call, response: Response) {
                    if(response.isSuccessful){
                    val resp = response.body?.string()
                    val gson = GsonBuilder().create()
                    val feed: List<Feed> = gson.fromJson(resp,Array<Feed>::class.java).toList()
                }
    
                override fun onFailure(call: Call, e: IOException) {
                    println("GAGAL")
                }
            })
    
        class Feed(val feed: List<Penyimpangan>)
    
        class Penyimpangan(val kodenik:String,val namakaryawan:String, val kodebagian:String, val tglupdate:String, val tglabsen:String,
                           val jamin:String, val jamout:String)
    The problem is, when I try to see the value of feed, it throws something like this :
    [com.example.penyimpangan_idm.ApprovalpenyimpanganActivity$Feed@4cef17c]
    My output from resp is like this :
    [{"kodenik":"2013129733","namakaryawan":"YASTI RIZKIA","kodebagian":"TRIE","tglupdate":"2019-12-09","tglabsen":"2019-12-09","jamin":"10:05","jamout":""}]
    a
    7 replies · 2 participants
  • w

    Wavecycle

    02/11/2020, 1:12 PM
    Hi there, first time poster...how would I call a function (indexInc) if that function is a value in a map? Thank you
    val indexInc = {if (index++ == memory.size - 1) memory.add(0u)}
    val commands = mapOf(">" to indexInc, "<" to indexDec)
    ❤️ 1
    i
    1 reply · 2 participants
  • a

    Ani Mehta

    02/12/2020, 11:27 PM
    Hey, sorta new here, coming from Golang. I was after a replacement for
    waitGroup
    , build my own, shockingly bad one...
    // TODO: Fix this hacky parallelism
    var awaitingResponse = 0
    for (v in needsResponses) {
        GlobalScope.launch {
            while (awaitingResponse >= 30) {
                delay(5)
            }
            awaitingResponse++
            // send API request, record response
            awaitingResponse--
        }
    }
    
    sleep(1000) // needed in order to not just skip before any request is sent off
    while (awaitingResponse > 0) {
        sleep(5000)
    }
    For reference it iterates over a map in parallel, what's a better way of doing this? There's an issue currently where it sometimes proceeds before all responses are fetched/ recorded
    r
    e
    +1
    4 replies · 4 participants
  • d

    Dawid Hyzy

    02/13/2020, 2:05 AM
    Hello, I just implemented checkbox on my recycler view, but I think I encountered a bug, so whenever I clicked on the first index, suddenly the item on the 11th index get clicked, it also apply whenever I click on 2nd item, the 12th item also get clicked. Is this a bug ? I need some assistance, thanks. For additional info, my adapter :
    class RecyclerViewAdapter(val feed: List<ApprovalpenyimpanganActivity.Penyimpangan>): RecyclerView.Adapter<CustomViewHolder>(){
    
    
        override fun getItemCount(): Int {
            return feed.count()
        }
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
            val layoutinflater = LayoutInflater.from(parent?.context)
            val row = layoutinflater.inflate(R.layout.penyimpanganlayout, parent, false)
            return CustomViewHolder(row)
        }
    
        override fun onBindViewHolder(holder: CustomViewHolder, position: Int){
            val feed = feed.get(position)
            holder.view.textView5.text = feed.namakaryawan + " - " + feed.kodenik + "\n" +
                                            feed.jamin + " - " + feed.jamout + "\n" +
                                            "Tanggal : " + feed.tglabsen
            holder.view.checkBox.setOnClickListener{
                println(position)
                println("CLICKED")
                println(feed)
            }
        }
    
    }
    
    class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view){
    
    }
    My data class :
    data class Penyimpangan(
            @SerializedName("kodenik") val kodenik : String,
            @SerializedName("namakaryawan") val namakaryawan : String,
            @SerializedName("kodebagian") val kodebagian : String,
            @SerializedName("tglupdate") val tglupdate : String,
            @SerializedName("tglabsen") val tglabsen : String,
            @SerializedName("jamin") val jamin : String,
            @SerializedName("jamout") val jamout : String
        )
    b
    r
    4 replies · 3 participants
  • y

    Yugandhar

    02/13/2020, 6:49 AM
    What is the difference between arrayof and IntArrayof and intArrayOf in kotlin
    a
    1 reply · 2 participants
  • s

    Saku Ytti

    02/13/2020, 7:18 AM
    Supppose I have kotlin product and I want to make parts of it scriptable by users run time. Could I load strings as kotlin script runtime, pass them objects and have them do something to those objects and return another object? Neither security or performance is important, but of course nice to have.
    d
    r
    8 replies · 3 participants
  • m

    Mark

    02/15/2020, 5:56 AM
    Is there a better way to write
    listOfStuff.asSequence().mapNotNull { fromStuffToSomethingOrNull(it) }.firstOrNull()
    a
    m
    +1
    12 replies · 4 participants
  • l

    Lukas Kraushofer

    02/16/2020, 3:43 PM
    hi, who can help me with IntelliJs 'JS Client and JVM Server | Gradle' Kotlin Project? building the project and starting the jvm (netty) server is working but the static js asset can't be loaded, is there some documentation I'm missing?
    d
    1 reply · 2 participants
  • j

    johnfn

    02/17/2020, 5:05 AM
    in kotlin i can do something like
    fun log(x: Int) { ... }
    fun log(x: String) { ... }
    fun log(x: Boolean) { ... }
    to have log take 3 different types of values
    s
    1 reply · 2 participants
  • j

    johnfn

    02/17/2020, 5:05 AM
    is there any way to extend this so log() could take more than 1 parameter
    g
    7 replies · 2 participants
  • s

    Slackbot

    02/17/2020, 5:06 AM
    This message was deleted.
    :thread-please: 2
    m
    1 reply · 2 participants
  • j

    johnfn

    02/17/2020, 10:07 PM
    is there any way to get the type of an anonymous object? e.g. if i do
    object { val x = 1 }
    and then i want to make a list of them, how would i write it? ideally, something that i could put in ???
    class Foo {
      private val myList = mutableListOf<???>()
      private fun addItem(x: Int) =
        myList.add(
          object { val x = x }
        )
    }
    s
    c
    10 replies · 3 participants
Powered by Linen
Title
j

johnfn

02/17/2020, 10:07 PM
is there any way to get the type of an anonymous object? e.g. if i do
object { val x = 1 }
and then i want to make a list of them, how would i write it? ideally, something that i could put in ???
class Foo {
  private val myList = mutableListOf<???>()
  private fun addItem(x: Int) =
    myList.add(
      object { val x = x }
    )
}
s

Shawn

02/17/2020, 11:01 PM
Any
👍 1
anonymous objects that don’t explicitly implement an interface or extend a class will just inherit from
Any
like everything does by default
but that won’t let you access your
x
val
if all the objects you’ll have in that list have the same shape (i.e. the same properties/functions defined on them), then you can declare an interface and have the objects implement them (or just declare and instantiate data classes)
if that doesn’t match your use case and you just want arbitrary mappings between keys and values, use a
Map
but you’ll never be able to have a strongly typed, arbitrarily-defined object anywhere that’s not within the scope of a function
👍 1
c

Chenn

02/18/2020, 8:25 AM
val obj = js("{}")
    obj["type"] = type
This is how I put a key - value pair in an anonymous object in kotlin. Maybe it helps.
val obj: dynamic = object{}
    reducers.forEach { obj[it.key] = it.value}
This practically generates the same code..
s

Shawn

02/18/2020, 3:59 PM
is that for Kotlin/JS?
js()
isn’t a stdlib function and
dynamic
isn’t a standard type on JVM, and presumably elsewhere
c

Chenn

02/18/2020, 4:01 PM
Yes, you got me there. Thought I was still in the #javascript channel. My bad
👍 2
View count: 4