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

    Johan Alkstål

    01/05/2021, 7:12 AM
    If I were to make a Kotlin Library project, how would I later on go about using it in a Kotlin Application project?
    m
    • 2
    • 4
  • c

    Colton Idle

    01/05/2021, 1:44 PM
    Is there an easy way to use TimeUnit class to specify 30 minutes for example? I found myself doing
    val thirty_mins = 30 * 60_000
    but there has to be a way to just do TimeUnit.Minutes(30) right?
    v
    l
    +3
    • 6
    • 12
  • m

    Max Deineko

    01/05/2021, 3:10 PM
    Hi, I'm trying (and so far failing) to understand why evaluating the following code in a scratch file in idea results in unexpected (for me) output:
    val l = mutableListOf("a")
    l[0] = "b"
    val x = l.first()
    println("""$x=${l.first()}""")
    ⇒
    val l: MutableList<String>
    
    val x: String
    a=b
    When evaluated with "Use REPL" or via run command from the menu it prints "b=b" instead. Am I missing something or is this a bug? (If this is too intellij-specific and not getting-started-related enough, I'll be happy to move this to #intellij)
    d
    • 2
    • 2
  • a

    alex cole

    01/06/2021, 4:19 AM
    Questions on operator overloading. I am trying to overload the “+” operator to add to objects together but am given an error. However with my own add routine the function works. Could some one explain why? Questions on operator overloading. I am trying to overload the “+” operator to add to objects together but am given an error. However with my own add routine the function works. Could some one explain why?
    class ArrayND  {
        var nDimensionalArray: ArrayList<Double> = arrayListOf()
        private var shape = arrayOf<Int>()
    
        constructor (ndArray: Array<Double>, shape: Array<Int>){
            nDimensionalArray = arrayListOf(*ndArray)
            this.shape = shape
        }
    
        private fun whatIsTheShape(): Array<Int> {
            return shape
        }
    
        fun add(b: ArrayND): ArrayND {
            if (shape.contentEquals(b.whatIsTheShape())){
                val x = arrayListOf<Double>()
                for(i in  0 until nDimensionalArray.size){
                    x.add(nDimensionalArray[i] + b.nDimensionalArray[i])
                }
                return ArrayND(x.toTypedArray(), shape)
            }
            else {
                return ArrayND(arrayOf<Double>(), arrayOf<Int>())
            }
        }
    
        operator fun plus(other: ArrayND){
            add(other)
        }
    
        fun print(){
            TODO("Work in more than one dimension")
            print("[")
            for(i in nDimensionalArray) {
                print("$i ")
            }
            print("]")
        }
    }
    e
    c
    v
    • 4
    • 5
  • h

    huehnerlady

    01/06/2021, 7:31 AM
    Hi, I now finished up the coursera course Kotlin for Java Developers. In there they do mention other courses, but I cannot find them on coursera. Does anybody know where I can find them?
    k
    • 2
    • 2
  • u

    Umar Ata

    01/06/2021, 7:33 PM
    Is it true kotlin executes on multi-core like Go?
    c
    • 2
    • 1
  • c

    Chills

    01/07/2021, 6:42 AM
    Is it efficient solving problems using Immutability? Also is it possible to solve all the problem using Functional Style 🙂
    t
    • 2
    • 7
  • a

    alex cole

    01/09/2021, 12:12 AM
    Hi, when using the get() operator overload, what type of info do you get when you put multiple parameters in there? for example
    val x = object[5,3]
    What type of data is the 5, 3 representing.
    e
    • 2
    • 41
  • i

    iBehnia

    01/09/2021, 7:15 PM
    hi there how can i add repository and dependency in my kotlin project?
    a
    • 2
    • 1
  • a

    alex cole

    01/10/2021, 1:54 AM
    What is the best way to check if any value in one array is greater that the value of another of equal size in each index?
    v
    e
    • 3
    • 13
  • n

    Nat Elkins

    01/11/2021, 4:03 PM
    I have a question about Intellij...what does the little blue square next to the folder represent? Project? Module? Library?
    m
    • 2
    • 5
  • n

    Nat Elkins

    01/11/2021, 4:25 PM
    Similar to https://dbup.readthedocs.io/en/latest/
    d
    m
    +3
    • 6
    • 20
  • n

    Nikhil

    01/12/2021, 7:30 AM
    Can anyone please explain me what is
    @IgnoreExtraProperties
    in Firestore with an example?
    :stackoverflow: 3
    m
    v
    • 3
    • 2
  • d

    Daniele B

    01/12/2021, 1:37 PM
    On a specific class I want to define many methods (let’s say 50), but I want to group these methods in separate files by topic (let’s say files with 4-5 methods). I was able to achieve this by defining these “methods” as “extension functions” instead? Do you see anything particularly wrong with that?
    d
    • 2
    • 19
  • n

    Nat Elkins

    01/12/2021, 10:47 PM
    And I want to do
    call.respond(HttpStatusCode.OK,someJson)
    and have the content type be
    application/json
    d
    • 2
    • 2
  • g

    Grian

    01/16/2021, 5:34 PM
    Going to do GUI for the first time in kotlin for a small project, what would be a good, relatively simple to work with framework?
    🙌 1
    a
    r
    c
    • 4
    • 9
  • a

    alex cole

    01/17/2021, 2:59 AM
    Class type question? I have an untyped class in a class primarily holding a typed array hard typed to double. I would like to move it to type the class where the class property is the same type and am able to overload operators for handling different types of boxed primitives as well as different types of the class that I have build. What is the best way to move my untyped class to a typed class.
    class ArrayND { // the class that I want to type
      var elements: Array<Double> // the array that all my functions refer too.
      var shape: Array<Int>
      constructor (ndArray: Array<Double>, shape: Array<Int>) {
        elements = ndArray
        this.shape = shape
      }
      operator fun plus(other: ArrayND): ArrayND {}
      operator fun plus(other: Double): ArrayND {}
    }
    I have a lot of functions that use array lists and convert them
    .toTypedArray()
    to create
    ArrayND()
    . This also has caused a problem when trying to be able to type the array and I would like to know if there is a way that if no type is given I could give it a default type of
    Double
    ?
    n
    • 2
    • 2
  • s

    Scott Whitman

    01/17/2021, 4:21 PM
    How do people tend to unit test DSL functions like the
    address
    function below? What are some good practices to handle the
    Address.Builder
    dependency?
    fun main() {
        val address = address {
            street = "123 Any St."
            city = "Any city"
        }
        
        println(address)
    }
    
    fun address(lambda: Address.Builder.() -> Unit): Address {
        return Address.Builder().apply(lambda).build()
    }
    
    data class Address(
        val street: String,
        val city: String
    ) {
        class Builder {
            var street: String? = null
            var city: String? = null
            
            fun build(): Address {
                return Address(street!!, city!!)
            }
        }
    }
    j
    m
    • 3
    • 5
  • s

    Stefán Freyr Stefánsson

    01/19/2021, 1:14 PM
    Hello gang. Can anyone explain the kotlin artifact structure to me a bit? Specifically I’m interested in the kotlin-stdlib-jdk8 package. I’m creating a Quarkus app and I’m using Java 11 but it seems that I still have to declare a dependency on the -jdk8 package. As there is no -jdk11 package I assume this is all fine and correct… but I kind of want to understand what the idea behind this package is exactly.
    d
    v
    • 3
    • 9
  • n

    Nat Elkins

    01/21/2021, 3:32 PM
    What SQL clients are people using? I see https://github.com/JetBrains/Exposed is pretty popular (by GitHub stars), but it looks like you can't drop down to SQL without writing your own extension (albeit a simple one). Also, it isn't async. Is Exposed the preferred Kotlin SQL library?
    a
    c
    r
    • 4
    • 3
  • c

    Colton Idle

    01/21/2021, 7:04 PM
    Noob here when it comes to companion objects. I basically have a
    class Blah {
    companion object {
    //HERE
    }
    fun somemethod2(){
    //THERE
    }
    }
    How can I define a variable that can be used in "HERE" and "THERE"? I know I can define
    val MY_CONST
    to the top of the file (outside of class declaration) but doesn't that make it global to all my classes? I just want it in the scope of the companion and the class.
    l
    v
    • 3
    • 3
  • l

    Lqncer

    01/21/2021, 9:08 PM
    I'm new to Kotlin and I would like to learn it. My current state of knowledge with other programming languages, is I have a good amount of knowledge of the concepts in Java (just never really wrote any complex projects, just know the concepts superficially). I also have my hands on a bunch of the resources on the kotlin website, but wasn't sure what would be best as my "first" real programming language. Any recommendations?
    n
    m
    • 3
    • 3
  • d

    Daniele Segato

    01/22/2021, 10:13 AM
    Is there some documentation on how to inspect a
    CoroutineScope
    /
    CoroutineContext
    ? I would I unit test this function?
    fun createCoroutineScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    So in my test I have to check if the returned
    CoroutineScope
    is using a
    SupervisedJob
    or a particular
    Dispatcher
    how do I do that?? (or any other property of the context/scope)
    d
    • 2
    • 5
  • j

    Jesus Ochoa

    01/22/2021, 1:26 PM
    Hello, I recently discovered Kotlin and IDEA and been loving them both. i'm currently using Kotlin for a project where I have an API that handles the business logic and, apparently, people at administration don't fancy doing cURL requests and want a web and an android client to consume it. Am I better off doing the api and the two clients each in a separate project, for three total, or all in kotlin multiplatform?
    p
    a
    t
    • 4
    • 22
  • v

    vineethraj49

    01/24/2021, 10:00 PM
    hi, quick question; what's the difference between
    val foo
      get() = expensiveOrAllocFunc()
    vs
    val foo by lazy { expensiveOrAllocFunc() }
    d
    • 2
    • 1
  • w

    Wasim

    01/25/2021, 9:58 AM
    Hello everyone, I want to start android development. I just know basic syntax of Java like variable, data type, functions, loops, operators. I want to do android development in Kotlin. What should I learn now and what resources should I follow ? If you can show me a roadmap of Android development with Kotlin for a newbie that would be awesome.
    u
    a
    k
    • 4
    • 9
  • f

    F0X

    01/25/2021, 7:42 PM
    Is there some way to declare an extension function that takes multiple (two) extension receivers?
    r
    • 2
    • 1
  • a

    allan.conda

    01/26/2021, 7:46 AM
    <Can’t find a good answer in SO> What’s an idiomatic way to check if a list (or set) contains only one specific value? anything better than
    checkedSet.contains(value) && checkedSet.size == 1
    ?
    r
    t
    • 3
    • 10
  • a

    alex cole

    01/27/2021, 11:23 PM
    Generics question. I am trying to make a constructor where one value is accepted as
    T: Number
    and another value in the class is initialized as 0 but that type of Number. How do I do that?
    class Complex<T: Number> {
      var real: T
      var imaginary: T
    
      constructor (real: T) {
        this.real = real
        imaginary = 0.ofType(T) // this is where help is needed
      }
    
      constructor (real: T, imaginary: T) {
        this.real = real
        this.imaginary = imaginary
      }
    }
    e
    a
    +2
    • 5
    • 18
  • v

    vineethraj49

    01/28/2021, 8:08 PM
    what is the consensus on using local data classes? yay or nay?
    n
    m
    m
    • 4
    • 9
Powered by Linen
Title
v

vineethraj49

01/28/2021, 8:08 PM
what is the consensus on using local data classes? yay or nay?
n

nanodeath

01/28/2021, 8:10 PM
local, as in...defined inside a method? hm...I don't think I've ever done that
m

Matteo Mirk

01/29/2021, 8:55 AM
never done that… I can’t see the advantage at the moment
v

vineethraj49

01/29/2021, 8:56 AM
well; it beats Map<Triple<String, String, String>, T> in my case so :blob-shrug:
m

Matteo Mirk

01/29/2021, 8:58 AM
of course, a custom type always beats primitive obsession and complex collections combination, just I can’t see why declaring one local, as “inside a method”…is that what you mean?
v

vineethraj49

01/29/2021, 8:59 AM
hmm
m

Matteo Mirk

01/29/2021, 9:01 AM
In general I think it would be cleaner to declare it as top-level in a file, you can even make it private if its scope is restricted to only classes/functions inside the file
v

vineethraj49

01/29/2021, 9:03 AM
so I had this case where I had a collection<T> where T had 10+ attributes; but each T is uniquely identified by T.a, T.b, T.c and a stupid bug I caused was due to me doing
val map = collection.associateBy { Triple(it.a, it.b, it.c) }
and then doing
map.keys.filter { it.first == x }
instead of `map.keys.filter { it.second == x }`; simplest way to avoid that seemed to be; in the context of the function;
val map = collection.associateBy { K(it.a, it.b, it.c) }
and then
map.keys.filter { it.b == x }
and given
K
was only needed in the context of said function, didn't need to be pulled out or exposed (even with
internal
) what I'm not sure of; if this is a "recommended" pattern
m

Matteo Mirk

01/29/2021, 11:29 AM
If you pull it up and mark it
private
it won’t be exposed anywhere. If I were to read code with local data types it would look less readable to me, but I guess it’a a matter of taste. There are no guidelines on this that I know of.
m

mkrussel

01/29/2021, 1:04 PM
I would be fine with a local data class as long as the use for it seemed very specific to that function. I've never done it before, and I never used local classes in Java either. I always wind up feeling it is better to pull it up
View count: 1