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

    Davide Giuseppe Farella

    10/04/2020, 6:33 AM
    Good morning, I'm searching for any kind of resources ( book, courses, exercises, etc ) for learn Kotlin for a total beginner. I'm trying to introduce this awesome world to my girlfriend, but everything I found is bases on a preexisting Java knowledge. I know it would be better to know the programming basics ( the hardware, algorithms, data structures, concurrency, etc ) but on the other side I'm also a self learner and I skipped some basics concepts that I learned in a second time and sometimes, when starting to learn, the satisfaction to implement a timeout with a simple
    withTimeout
    is more important than the frustration in learning to use threads in Java
    p
    • 2
    • 1
  • p

    Pau

    10/05/2020, 11:43 AM
    Good afternoon guys, I am trying to deal with this issue that I cannot solve. How can I avoid the nullsafe call?
    val cardStats = mutableMapOf<String, Int>()
    Once the card is created in other map for example: "France" to "Paris", this is automatically created:
    cardStats = mutableMapOf("France" to 0)
    In the guessing function, if they miss it adds up fail attempts into the card:
    cardStats[ansDef] += 1
    But I get this:
    Operator call corresponds to a dot-qualified call 'cardStats[ansDef].plusAssign(1)' which is not allowed on a nullable receiver 'cardStats[ansDef]'.
    m
    v
    e
    • 4
    • 9
  • k

    Kenneth

    10/06/2020, 10:39 AM
    Shouldn’t
    find {}.let {}
    give me an Object and not Object? inside the let?
    d
    • 2
    • 2
  • p

    Pau

    10/06/2020, 11:51 AM
    Anyone can help me to link this test: A
    class Rectangle {
        val width: Int
        val length: Int
    
        constructor(_width: Int, _length: Int) {
            width = _width
            length = _length
        }
    }
    
    val rectangle = Rectangle()
    B
    class Rectangle {
        val width: Int
        val length: Int
    
        constructor(width: Int, length: Int) {
            width = width
            length = length
        }
    }
    C
    class Rectangle {
        val width: Int
        val length: Int
        
        constructor(_width: Int, _length: Int) {
            width = _width
            length = _length
        }
    
        constructor(_sizeA: Int, _sizeB: Int) {
            width = _sizeA
            length = _sizeB
        }
    }
    D
    class Rectangle {
        val width: Int
        val length: Int
    
        constructor(width: Int, length: Int) {
            
        }
    }
    E
    class Rectangle {
        val width: Int = 1
        val length: Int = 1
    
        constructor(width: Int, length: Int) {
            this.width = width
            this.length = length
        }
    }
    F
    class Rectangle() {
        var width: Int = 1
        var length: Int = 1
    
        constructor(width: Int, length: Int) {
            this.width = width
            this.length = length
        }
    }
    I am a bit confused 🧐 1. Signature uniqueness violation 2. Primary constructor call is absent 3. Reassigning previously 4. Uninitialized properties 5. No values passed for constructor pararmeters 6. Reassigning val because of name collision
    v
    t
    • 3
    • 6
  • m

    Max Beyer

    10/07/2020, 4:44 PM
    greetings all, I’m wondering about initializing objects via a constructor vs an extension function. Example via constructor:
    data class CarDTO(
        val make: String,
        val model: String,
        val year: Int
    )
    
    data class Car(
        val make: String,
        val model: String,
        val year: Int
    ) {
        constructor(carDTO: CarDTO) : this(
            make = carDTO.make,
            model = carDTO.model,
            year = carDTO.year
        )
    }
    Example via extension function:
    data class CarDTO(
        val make: String,
        val model: String,
        val year: Int
    ) {
        fun toCar(): Car {
            return Car(
                make = this.make,
                model = this.model,
                year = this.year
            )
        }
    }
    
    data class Car(
        val make: String,
        val model: String,
        val year: Int
    )
    Is there an advantage to using one of these over the other? I’ve been doing some research, but can’t find any arguments either way.
    t
    v
    • 3
    • 7
  • a

    Alex

    10/08/2020, 12:17 PM
    I'll post here my question. 🙂 I'm very new to Java/Kotlin - I've mostly been a php dev throughout my carrier, so just learning here. First question: How do I control JSON serialization when sending a POST to a controller action?
    @PostMapping("/")
    fun addAnnouncement(@RequestBody dto: AnnouncementDTO) {
        println(dto);
        manager.addAnnouncement(dto.toAnnouncement())
    }
    This is my body:
    {
      "text": "Hello",
      "occupant": "35A",
      "date": "2020-10-09"
    }
    It works. Second question: Why? I'm assuming this might not be even a kotlin-specific question, rather Spring, but as I said, I'm quite new at this so excuse some confusion. 🙂
    t
    c
    • 3
    • 8
  • a

    Alex

    10/08/2020, 12:22 PM
    Also... Do I commit
    gradle/*
    directory into VCS?
    v
    • 2
    • 2
  • v

    Valentin Metz

    10/08/2020, 3:34 PM
    I want an enum that holds a variable. Is that possible? (Example: Enum of Male or Female, but with a variable "height" that gets passed in constructor)
    v
    • 2
    • 6
  • v

    Valentin Metz

    10/08/2020, 4:52 PM
    Does Kotlin have a Ring-Array? (Or Dequeue or ringbuffer or however one calls it)
    a
    s
    • 3
    • 3
  • b

    Bonya

    10/08/2020, 8:41 PM
    Greetings folks, are there any good resources out there to help me get better at Kotlin? Help me out with some you have
    v
    j
    u
    • 4
    • 4
  • j

    Juan B

    10/09/2020, 1:54 AM
    Hi Everybody! .. I'm just doing my first steps in Kotlin after a long time using Groovy, so far I'm enjoying it. I have a question, probably simple but Im trying to get some traction. ❓ -> If I have an app which is using BigDecimal heavily, is there a way to avoid creating theBigDecimal explicitly when calling methods that expect a BigDecimal? (something like implicit transformation from integer to BigDecimal on the caller so you can call methods using just a integer) E.g. When instantiating this data class, I have to pass the salary as explicit integer:
    val employeeRunData = EmployeeRunData(annualSalary = BigDecimal(120000))
    Instead, I would like to do something like: <note there is not call to _BigDecimal(120000)_>
    val employeeRunData = EmployeeRunData(annualSalary = 120000))
    I would highlight that the annoyance is while writing unit test. Thank you all!
    m
    m
    +2
    • 5
    • 7
  • a

    Andrea Giuliano

    10/10/2020, 5:46 PM
    Hi folks, newbie question 🙂 I was trying to implement a class that is backed by a Map. You can initialise it with a key and a value, and you can merge two together (but not with clashing keys) Problem is the the plus operator, since the constructor does not allow me to pass a map (since I don’t want to give an anaemic control from outside). Is there any trick I’m missing here? I was thinking to have a private constructor that only ControlledMap could use, but then again I have to use the primary constructor. The other alternative is to change table to be var and initialise a random ControlledMap and then swap the table property (but I’d hate doing that) Any suggestions?
    class ControlledMap(type: Type, index: Int) {
        private val table = mapOf(type to index)
    
        fun get(type: Type): Int =
            table.getOrElse(type) { throw IllegalArgumentException("Trying to get a non existing content from ControlledMap") }
    
        operator fun plus(other: ControlledMap): ControlledMap {
            if (table.keys.any { other.table.containsKey(it) }) {
                throw IllegalArgumentException("Cannot merge ControlledMaps with clashing keys")
            }
    
    
            // want to return a new ControlledMap where table is the union of the 2 tables (this.table + other.table)
        }
    
    
        enum class Type {
            A,
            B,
            C,
            D
        }
    }
    m
    • 2
    • 2
  • d

    Daniele B

    10/11/2020, 12:17 AM
    I have a list of numbers:
    val numbers = listOf(1,2,4,8,11,14)
    I would like to create a new list with the differences between a number and the one that is 2 indexes before it. In this case the results would be:
    val differencesTwoIndexesApart = listOf(3,6,7,6)
    is there an easy way to do that with Kotlin high-order functions? or is an imperative for loop the best way?
    a
    e
    v
    • 4
    • 16
  • b

    Brutus5000

    10/12/2020, 8:54 AM
    I can compile the following code which at runtime will always end up with an NPE (getTransition returns null)
    @Test
        fun reproducibleNPE() {
            ZoneId.of("Europe/Berlin").rules.getTransition(LocalDateTime.MIN).isOverlap
        }
    Looks like I can't trust Java platform calls. But what are the rules? When can I trust it?
    m
    • 2
    • 2
  • i

    ildar.i [Android]

    10/12/2020, 1:35 PM
    How can I parse sealed class from string? With enum I can iterate over its values and find it, but can I do the same with sealed class?
    d
    v
    a
    • 4
    • 4
  • t

    tseisel

    10/12/2020, 2:09 PM
    Is there a Kotlin library (or at least a JVM library) to compute differences between 2 `List`s ? Something like:
    fun <T> listDiff(original: List<T>, revised: List<T>): List<DiffOp<T>>
    
    sealed class DiffOp<T> {
      class Add<T>(val element: T, val index: Int) : DiffOp<T>()
      class Remove<T>(val element: T, val index: Int) : DiffOp<T>()
    }
    I find myself needing this kind of feature quite often. I've searched the web like crazy, but it seems that Myer's Diff Algorithm has only been implemented for diffing text, not collections. Swift's standard library implements it as CollectionDifference. Maybe this could be a nice library to have for Kotlin Multiplatform ?
    v
    a
    • 3
    • 6
  • s

    Slackbot

    10/12/2020, 4:29 PM
    This message was deleted.
    a
    • 2
    • 1
  • a

    Andrea Giuliano

    10/13/2020, 4:10 PM
    Hi guys, given I have a map like
    val myMap = sortedMapOf<String, Collection<Int>>()
    Is there a way to put into the map and overflow in the collection in case the key already exist in the map?
    d
    n
    • 3
    • 7
  • a

    Andrea Giuliano

    10/14/2020, 8:31 AM
    Having fun with basic structs, and was looking into intersect 2 ordered IntArray together. I know I can do something like
    first.intersect(second.toList()).toIntArray()
    but this is not really O(n). It takes more time than just using standard comparison one by one (using the property that the 2 IntArrays are ordered). I wonder if there is something elegant to solve this in Kotlin? An ugly way to do this fast would be with something like
    private fun intersection(a: IntArray, b: IntArray): IntArray {
            val c = IntArray(min(a.size, b.size))
            if (c.isEmpty()) {
                return c
            }
            var i = 0
            var j = 0
            var k = 0
            while (i < a.size && j < b.size) {
                val aa = a[i]
                val bb = b[j]
                val comparison = aa - bb
                if (comparison == 0) {
                    c[k++] = aa
                    i++
                    j++
                } else if (comparison < 0) {
                    i++
                } else {
                    j++
                }
            }
            return c.copyOf(k)
        }
    n
    e
    • 3
    • 14
  • j

    Jgafner

    10/14/2020, 8:21 PM
    Hi Can someone please explain me this code ?
    fun aFun() : ObjectA?{
    val (side,line) = when(someData){
          is TypeA -> thread.position?.let { diffData.linesMapper.findFileLocation(it) } ?: return null
          is TypeB -> ... ?: return null
    }
    
    return ObjectA(side,line)
    when ObjectA constructor is expecting null safe type of side and line. in case of is TypeA happen and it return null what will be the values in side and line ? tnx
    n
    • 2
    • 2
  • j

    Juan B

    10/14/2020, 10:44 PM
    Hi all, I'm having some problems using BigDecimal, I'm not sure if I'm missing anything or there is some issues with the toBigDecimal() method. I'm trying to create an expected value to validate a business logic. I'm trying the expected value to be a big decimal equals to 100.00 (note 2 decimal places). The problem is that I cannot get this amount; it always come as 100.0 (a single decimal place, which make the assert to fail) Here is a snippet code that shows the issue: https://pl.kotl.in/O8tUt3IxC
    e
    n
    • 3
    • 8
  • f

    Fady Emad

    10/15/2020, 12:26 AM
    Hi all, I’m new here and i found a millions 🤪 of channels and don’t know where to start, and best channels to follow, any suggestions?
    a
    m
    • 3
    • 2
  • j

    Jonexume

    10/15/2020, 5:23 AM
    Good evening just joined and new to kotlin. I was wondering if anyone had a good up to date resource for learning kotlin besides the website. Any resources you recommend. Thank you in advance.
    f
    d
    +3
    • 6
    • 8
  • d

    Daniele B

    10/15/2020, 9:53 PM
    data class City (
        val name : String = "",
        val country : String = "",
        val population : Int = 0,
    )
    
    val cities = { listOf(
        City("a", "1", 1305770),
        City("b", "1", 556934),
        City("c", "2", 1924701),
        City("d", "3", 5785861),
        City("e", "3", 4467118),
    ) }
    q
    e
    n
    • 4
    • 5
  • d

    Daniele B

    10/16/2020, 1:06 AM
    mylist.zip(mylist.drop(1)) { a, b -> myfunction(a,b) }
    is there a way to zip 3 lists instead of 2? something equivalent to this?
    zip(mylist, mylist.drop(1), mylist.drop(2)) { a, b, c -> myfunction(a,b,c) }
    I would like to create a new list of values, which are calculated based on the latest 3 values
    r
    e
    v
    • 4
    • 27
  • s

    Sebastian Galkin

    10/19/2020, 4:00 AM
    Where is the reference documentation for the stdlib? I know about https://kotlinlang.org/api/latest/jvm/stdlib/ but I want more detail. For example, what are all
    List
    constructors, what are the performance characteristics of
    List.plus
    etc.
    n
    • 2
    • 6
  • s

    Son

    10/19/2020, 4:29 PM
    https://pl.kotl.in/Fa9favTpr I was getting this error and as a newbie I had a hard time determining why I could not do this (i.e. treating lambda as a function reference). Should the compiler error be more helpful?
    fun fn1(x: Int): Boolean = x % 2 == 0
    fun fn2(x: Int): Boolean { return x % 2 == 0 }
    
    fun main () {
        val listNum = listOf(1, 2, 3, 4, 5, 6)
        val fn3: (Int) -> Boolean = { it % 2 == 0 }
    
        println(listNum.filter(::fn1)) // compiles and outputs [2, 4, 6]
        println(listNum.filter(::fn2)) // compiles and outputs [2, 4, 6]
        println(listNum.filter(fn3)) // compiles and outputs [2, 4, 6]
    
        // e: org.jetbrains.kotlin.util.KotlinFrontEndException: Exception while analyzing expression at (17,13)
        println(listNum.filter(::fn3)) // Error
    }
    r
    v
    • 3
    • 14
  • j

    Jacob

    10/19/2020, 9:00 PM
    Is there any rule as to when I should use
    .not()
    and when I should use good old
    !
    https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/not.html
    n
    t
    +6
    • 9
    • 18
  • h

    huehnerlady

    10/20/2020, 9:53 AM
    I am currently migrating some groovy tests to kotlin. With that I want to write a kotlin (extension?) function to set an immutable property by name with a given value in my constructor. So I have a variable which includes a property name and a variable which includes so if you have a data class:
    data class Foo(val id: Int? = null, val someStringProperty: String? = null)
    I would like to write something like
    createFoo(propertyName: String, propertyValue: Any): Foo
    which I can then use like:
    val foo1 = createFoo("id", 5) // Foo(id = 5, someStringProperty = null)
    val foo2 = createFoo("someStringProperty", "someString") // Foo(id = null, someStringProperty= "someString")
    Any idea how I can achieve that? It might look very hacky… but it would be really useful for the tests we have (and to convinde colleagues who love grrovy a bit more 😉 )
    ☑️ 1
    v
    d
    s
    • 4
    • 32
  • w

    Wavecycle

    10/20/2020, 12:36 PM
    Hi, I'm having trouble with my IDEA setup. I'm trying to get the kotlinx coroutines imported and working, but along the way I'm having trouble with my build.gradle file, namely "code insight unavailable" and then it suggests "try re-importing the linked Gradle project". What exactly am I supposed to do here? Still learning, thank you
    d
    • 2
    • 5
Powered by Linen
Title
w

Wavecycle

10/20/2020, 12:36 PM
Hi, I'm having trouble with my IDEA setup. I'm trying to get the kotlinx coroutines imported and working, but along the way I'm having trouble with my build.gradle file, namely "code insight unavailable" and then it suggests "try re-importing the linked Gradle project". What exactly am I supposed to do here? Still learning, thank you
d

deactivateduser

10/20/2020, 12:37 PM
have you tried the suggested? did it resolve the issue?
w

Wavecycle

10/20/2020, 12:41 PM
I'm not quite sure what I'm supposed to remove and reimport. If I go to my project structure and look in the Libraries menu item on the left, there are 7 libraries listed, e.g. "Gradle: org.jetbrains.kotlin:kotlin-stdlib..." Is it asking me to remove those and reimport them? Am I supposed to do it somewhere else? Thanks
d

deactivateduser

10/20/2020, 12:44 PM
maybe you can check this out... https://www.jetbrains.com/help/idea/work-with-gradle-projects.html#gradle_refresh_project
w

Wavecycle

10/20/2020, 12:52 PM
Thanks, that solved problem 1, autocomplete working //I've never used this Gradle window before.
d

deactivateduser

10/20/2020, 12:53 PM
👍
😁 1
View count: 1