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

    Christian Janev

    07/09/2020, 11:10 PM
    toBePercent = (toBePercent.toFloat() / 100).toString()
    I have this line of code and whenever I make toBePercent into 5 it converts it to "0.05" (good) but whenever I make toBePercent into 10 or above it outputs "0.0"
    d
    d
    • 3
    • 9
  • s

    Slackbot

    07/10/2020, 7:42 AM
    This message was deleted.
    d
    m
    • 3
    • 5
  • k

    Karlo Lozovina

    07/10/2020, 6:15 PM
    is there a
    dropLast
    like function, that modifies list inplace, instead of returning a new one?
    s
    • 2
    • 2
  • m

    Mark

    07/11/2020, 2:17 AM
    Function visibility question here: I have a function that is only (and should only ever be) called by other functions (all inline) in the same file. I see that it must have at least the same visibility as the calling inline function. However, I don’t want to expose that function polluting the API. Is there any way to not expose that function signature outside of the file? I was hoping something like “private inline fun…” might work, but no.
    t
    t
    d
    • 4
    • 3
  • a

    Alexey Anufriev

    07/14/2020, 11:52 PM
    why Kotlin decided to have data type to be specified after variable name? this has some limitations, for example code completion with java IDEA suggests you a variable name based on the type, but in Kotlin type is unknown at the moment when variable name is specified..
    r
    i
    +6
    • 9
    • 11
  • m

    Mark

    07/15/2020, 9:19 AM
    Is there a flow operator to consolidate consecutive items under certain conditions? For example, suppose there is a flow of Strings and I want to concatenate consecutive single character strings like this: (‘a’, ‘bc’, ‘d’, ‘e’, ‘f’, ‘gh’) to (‘a’, ‘bc’, ‘def’, ‘gh’)
    m
    • 2
    • 2
  • p

    poohbar

    07/16/2020, 8:19 PM
    it's telling me that the
    it.get
    is expecting
    Nothing
    .. why?
    d
    • 2
    • 2
  • c

    Christian Sousa

    07/17/2020, 3:39 PM
    Hello! How can one write something like this in Kotlin?
    let finished = false
    for (let i = 0; i < restrictions.length && !finished; i++) {
    
          finished = ...
    
        }
    d
    d
    +2
    • 5
    • 6
  • c

    Christian Janev

    07/18/2020, 7:50 PM
    any reason why this crashes when i click on the menu item?
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.convert -> startActivity(Intent(this, unitConvert::class.java))
        }
        return super.onOptionsItemSelected(item)
    }
    r
    • 2
    • 1
  • p

    Praveen Talari

    07/19/2020, 2:36 PM
    Issue: Gradle application plugin using Kotlin is not compiling Java files. Steps: 1. Create gradle application gradle init Select type of project to generate: 1: basic 2: application 3: library 4: Gradle plugin Enter selection (default: basic) [1..4] 2 Select implementation language: 1: C++ 2: Groovy 3: Java 4: Kotlin 5: Swift Enter selection (default: Java) [1..5] 4 Select build script DSL: 1: Groovy 2: Kotlin Enter selection (default: Kotlin) [1..2] 2 2. Add SomeJavaClass.java file beside App.kt file class SomeJavaClass{ public void m(){ System.out.println("x"); } } 3. Try to access SomeJavaClass in App.kt main method SomeJavaClass().m() Excepted Output: Should be able to run Actual Output: no compile issues but crash because of NoClassDefFoundError
    g
    • 2
    • 3
  • j

    Joe Masilotti

    07/20/2020, 12:47 AM
    Does anyone have any insight on how I could build this radial selection in Android? This is a screenshot from the iOS app. I’m still pretty new to Android and I’m not even sure where to start Googling.
    :stackoverflow: 4
    r
    • 2
    • 1
  • c

    Christian Sousa

    07/20/2020, 4:31 PM
    One question, in Typescript I’m able to do something like this:
    type CustomReturnType = (a: String, b: Int) => String
    
    export class Foo {
      private aggregator: CustomReturnType[] = [
        (a: String): String => a,
        (a: String, b: Int) => {
          ...
          return "something"
        }
      ]
    }
    On Kotlin, I did something like this:
    class Foo {
      var aggregator: MutableList<(a: String, b: Int) -> String> = mutableListOf()
    
      fun first(a: String): String {
        return a
      }
    
      fun second(a: String, b: Int) {
        ...
        return "something"
      }
    
      constructor() {
        aggregator.add(first)
        aggregator.add(second)
      }
    }
    Problem is I’m getting a Type mismatch
    Required: (String, Int) -> String
    Found: String
    Does anyone know why I can’t or is there something I’m doing wrong?
    t
    • 2
    • 3
  • g

    Gus

    07/20/2020, 5:41 PM
    Hey folks. I have a sequence and I want to create a function to group the elements in that sequence on the fly (i.e., without waiting until the last element on the original sequence). Can I do that with a purely functional approach? I can get it to work with
    sequence {}
    but it feels like an overkill to use a couroutine for this. Consider the code below:
    data class MessageWithExpiry(
        val messageSerialized: ByteArray,
        val expiryDate: ZonedDateTime
    )
    
    data class Batch(
        val messages: Array<ByteArray>,
        val latestMessageExpiryDate: ZonedDateTime
    )
    
    fun batchMessages(messages: Sequence<MessageWithExpiry>): Sequence<Batch> = TODO()
    Each
    Batch
    should contain an array of messages (taken from
    MessageWithExpiry.messageSerialized
    ) which collectively don't exceed 8 MiB. If
    messages
    is empty, the result should be empty too. If all the
    messages
    fit in one batch (i.e., they don't exceed the 8 MiB limit collectively), then only one batch should be output -- otherwise, multiple `Batch`es should be output. Additionally, each batch should have the latest expiry date of any message in the batch. Intuitively, I think I should split this in two parts: One for the batching itself (using something like
    Sequence.scan
    but not that per se), and another for the computation of each
    Batch.latestMessageExpiryDate
    (using
    Sequence.map
    ). But I don't think
    Sequence.scan
    ,
    Sequence.reduce
    ,
    Sequence.fold
    or any of their variations would help me do the first part. Any pointers on whether/how I can do this using a functional approach?
    t
    • 2
    • 6
  • c

    Christian Sousa

    07/22/2020, 1:40 PM
    Hey guys! Anyone knows what should something like this be implemented in Kotlin?
    export interface Item {
      [label: string]: string[];
    }
    
    export interface SequenceMap {
      '1': string[] | Item ;
      '2': string[] | Item ;
    }
    I know that I can use a
    sealed class
    to mimic the
    string[] | Item
    . But what is really bugging me is how can I do something like the Item interface? I’m not that used to Kotlin but this is something somewhat trivial in Typescript. Any help would be great! Thanks!
    r
    t
    • 3
    • 26
  • d

    Doug

    07/24/2020, 5:36 AM
    is there a simpler way to write something like:
    val urlIds = ArrayList<Long?>
    
    for (u in urls) {
      urlIds.add(u.id)
    }
    p
    t
    • 3
    • 3
  • m

    Mervil

    07/24/2020, 7:47 PM
    I'm brand new to Kotlin, and OOP in general. I've been reading books and taking introductory courses online. But there are some things I just can't understand currently. Right now I'm learning about "Scoping Functions" such as apply, with, let, run, etc. I am really struggling to understand these functions, maybe because I'm having trouble understanding what a "receiver" is, and what the difference between "it" and "this" is, and when to use one vs the other. Can somebody please explain "receivers" and the difference between "it" and "this"? I do have a basic understanding of extender functions. Thanks!!
    a
    m
    j
    • 4
    • 10
  • j

    Ju

    07/25/2020, 12:51 PM
    i know java where is the best way to start Kotlin? any suggestions?
    m
    • 2
    • 2
  • m

    Manuel Pérez Alcolea

    07/26/2020, 2:09 AM
    is there a better way to write this in Kotlin? I'm not trying to solve anything real, just playing around
    fun File.asSequence(): Sequence<String> {
        val reader = this.bufferedReader()
        return sequence {
            while (true) {
                yield(reader.readLine() ?: break)
            }
        }
    }
    and is combining scopes frown upon? for example
    fun File.asSequence2(): Sequence<String> = this.bufferedReader().let {
      // now sequence { } allows me to have `it` for the reader and `this` for the sequence
    }
    (ignore the fact that that first line in particular got really long)
    t
    • 2
    • 1
  • b

    blue

    07/27/2020, 2:56 PM
    Hi everyone, I am new to Kotlin, I have been learning Kotlin thru hyperskill.org for past few weeks. Currently I am little confused with a small Quotation in Hyperskill study material, Can someone help me? In Kotlin do we need to initialize the class level mutable ( 
    var
     ) property during declaration? *T*he study material says -
    full syntax for any property in Kotlin:
    var <propertyName>[: <PropertyType>] [= <property_initializer>]
        [<getter>]
        [<setter>]
    Initializer, getter, and setter are optional here, but you need to initialize your variable if you don’t want to specify its type. Otherwise, the compiler will warn you.
    But my code snippet is throwing compile error. Did I miss something?
    class User {
        var firstName: String 
        var lastName: String
    }
    j
    t
    +2
    • 5
    • 10
  • c

    Carrascado

    07/27/2020, 5:08 PM
    I was reading this: https://blog.jetbrains.com/kotlin/2020/07/kotlin-1-4-rc-released/ May I ask why If Kotlin is a programming language... it talks a lot about things like "Improved *.gradle.kts IDE support"? Isn't that topic about improving the IDE (IntelliJ IDEA or whatever) and not about improving the language syntax or something like that?
    ❤️ 1
    i
    • 2
    • 1
  • c

    Carrascado

    07/27/2020, 5:08 PM
    Or are they improving the language syntax so the IDE has it easier? I don't understand
    k
    j
    o
    • 4
    • 6
  • c

    Carrascado

    07/27/2020, 5:18 PM
    Does anyone know why would Kotlin need to target specifically Java 8 for compiling in some cases? What features of Kotlin do need that? It has happened to me after trying some property based testing in Kotest (https://github.com/kotest/kotest), it said
    Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option
    and it got fixed setting the project to compile into Java 8 with kotlinOptions What I understand from the error message is that some part of the library is directly injecting bytecodes meant for the JVM 1.8? I'd like to know more about this kind of details but I don't find much info searching by myself, maybe I'm not writing the right keywords when searching
    t
    • 2
    • 1
  • m

    matt tighe

    07/27/2020, 7:47 PM
    Why does the
    init
    block in this case warn:
    Leaking 'this' in constructor of non-final class A
    but not in the
    .apply
    case? Is the receiver block guaranteed to run after construction of
    A
    completes somehow, or is this just a case that isn’t caught by the linter?
    abstract class A(injectedB: B) {
        init {
            injectedB.observeA(this)
        }
        
        val constructedB = B().apply {
            observeA(this@A)
        }
    }
    
    class B {
        fun observeA(a: A) {}
    }
    t
    m
    • 3
    • 2
  • q

    queen-of-idleness

    07/28/2020, 9:33 AM
    Hi Folks, I post this in getting-started because I just switched from Scala (http4s, cats) to Kotlin. Please feel free to point me to another channel if there is a better fitting one. As a context you might consider my perspective is quite Scala driven.
    Given
    Two external services should be called successively. Calling service B depends on the response of service A. The responses are wrapped in this monad result type. There are two places where an error response can happen. In that case the flow should be aborted immediately and the error should be converted to a http response with a human readable body. We want to stay with the standard library, http4k, result4k and coroutines. So we don't want to use a library like arrow or similar.
    Issues
    1. Is there a better mechanism to chain the flow? 2. Should calling external services be wrapped in some structure like 
    Future
     or 
    Deferred
     ? We might have to wait for their result but can't do anything in parallel in the meantime. This is the simplified, compiling pseudo code:
    data class HttpResponse(val status: Int, val body: String)
    
    typealias RequestA = String
    typealias ResponseA = String
    typealias ErrorA = String
    
    typealias RequestB = String
    typealias ResponseB = String
    typealias ErrorB = String
    
    fun someFunction(
            callServiceA: (RequestA) -> Result<ResponseA, ErrorA>,
            callServiceB: (RequestB) -> Result<ResponseB, ErrorB>,
            input: String
    ): HttpResponse =
            callServiceA(input)
                    .mapFailure { HttpResponse(409, "please provide a valid id") }
                    .flatMap { responseA ->
                        callServiceB(responseA)
                                .mapFailure { HttpResponse(401, "you don't exist") }
                                .map { responseB -> HttpResponse(200, responseB.capitalize()) }
                    }.get()
    👍 2
    p
    • 2
    • 2
  • c

    Christian Sousa

    07/28/2020, 10:46 AM
    Anyone knows why this is giving me a return value of false when it should be true?
    "\b[01]+\b".toRegex().matches("11010011")
    Basically what I’m trying to do is just check if there is something else besides 0 or 1 in the string. I tried also with
    "/^[0-1]+$/".toRegex().matches("11010011")
    But with the same result..
    o
    s
    m
    • 4
    • 9
  • m

    matt tighe

    07/28/2020, 9:43 PM
    is
    this::class.java.simpleName
    using reflection?
    r
    i
    • 3
    • 5
  • c

    Christian Sousa

    07/29/2020, 9:31 AM
    Anyone can enlighten me why something like this on typescript works:
    let binaryString = "001110110001010001110100110111100100"
    console.log(parseInt(binaryString, 2))
    // output: 15859142116
    But not on Kotlin:
    var binaryNumber:String = "001110110001010001110100110111100100"
        
        try {
        var retr = binaryNumber.toInt(2)
        println(retr)        
        } catch(error: Throwable){
            println(error)
        }
    // java.lang.NumberFormatException: Invalid number format: '001110110001010001110100110111100100'
    d
    • 2
    • 2
  • k

    Konstantin Petrukhnov

    07/30/2020, 4:39 PM
    Is there some easy way to use "when" with ByteArray ? I have bunch of 2-3 byte arrays, and need to have switch. if(a.contentEquals(b)) is a valid alternative, but I was looking for something with "when(a)". (for 1.4-*)
    s
    a
    • 3
    • 4
  • c

    Carrascado

    07/30/2020, 5:50 PM
    Is it ok to use Java packages for organizing Kotlin code? Or does Kotlin have its own "package" concept? I'm not very sure of what to click (It's AndroidStudio)
    w
    m
    • 3
    • 3
  • m

    matt tighe

    07/31/2020, 7:55 PM
    What’s the deal with this? I thought that children of enum classes were objects, so they should be able to be referenced statically? Why would a getter be necessary when an instance of the enum class can never change? I can’t edit the image apparently, but I’ve added one that’s more clear in the thread below
    t
    • 2
    • 2
Powered by Linen
Title
m

matt tighe

07/31/2020, 7:55 PM
What’s the deal with this? I thought that children of enum classes were objects, so they should be able to be referenced statically? Why would a getter be necessary when an instance of the enum class can never change? I can’t edit the image apparently, but I’ve added one that’s more clear in the thread below
t

tseisel

07/31/2020, 8:00 PM
All enum constants are initialized in order when any of them is used for the first time. Since you are initializing a property of each constant whose value is immediately computed from Banana, Banana is not initialized yet. You have to use getters to make it work (just like
isOrange
)
💯 2
View count: 2