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

    Matt

    03/18/2019, 3:56 PM
    Is there way of getting the whole entry set back from a map rather than just the value?
    d
    n
    • 3
    • 11
  • m

    matt tighe

    03/19/2019, 6:13 PM
    is there a way to skip the intermediate assignment here?
    data class VersionCode(val code: String) {
        val major: Int
        val minor: Int
        val patch: Int
        init {
            val (first, second, third) = code.substringAfter('v').split('.')
            major = first.toInt()
            minor = second.toInt()
            patch = third.toInt()
        }
    }
    j
    b
    +3
    • 6
    • 6
  • g

    Guru

    03/20/2019, 4:42 AM
    How to restrict any one to add an extension method/properties to a particular class? My team works at different location and they are trying to put similar functionality on the same class by creating extensions in two different *.kt files. They were not known that they already have similar functionality being implemented in other module unless we integrate finally to a single file/module... there is a code reusability issue here.. any suggestions ?
    k
    j
    a
    • 4
    • 5
  • i

    ivano

    03/20/2019, 1:53 PM
    can I pass a Pair inside a when(condition) ?
    s
    f
    k
    • 4
    • 11
  • i

    ivano

    03/20/2019, 1:54 PM
    in other words I want to check two conditions inside the when statement
    k
    • 2
    • 10
  • g

    gregorbg

    03/20/2019, 5:21 PM
    Is there any more Kotlin-esque way to achieve the effect outlined here?
    Obfuscated_code_snippet.kt
    w
    r
    +2
    • 5
    • 10
  • d

    David Holmes

    03/20/2019, 6:26 PM
    If I have a function that takes a
    String
    and parses it to return some
    MyDataClass
    , is it idiomatic in Kotlin to return
    MyDataClass?
    which is
    null
    if the input String doesn't match the pattern? Or should I use a
    Result
    or throw an exception or something? In this case returning
    null
    would happen "normally" and would not be exceptional in any way
    r
    e
    • 3
    • 7
  • n

    Nikolai

    03/21/2019, 10:14 AM
    Hi, everyone! I developed a few apps using Kotlin for Android but still don't know how exactly gradle and all it's commands work. How you should place gradle files and so on. Now when I am trying to work with multiplatform projects things became even worse. Is where any books, articles, posts, manuals that I can read and know everything about every line in gradle files, tasks and how it's work?
    a
    • 2
    • 1
  • f

    Fredrik Pe

    03/21/2019, 1:50 PM
    Why is
    if (list?.isEmpty())
    not allowed when
    if (list?.isEmpty() == true)
    is? You are still not specifying null behaviour...
    d
    f
    +3
    • 6
    • 13
  • d

    ddlucas

    03/21/2019, 3:58 PM
    2 questions: 1) why is it hard to find current examples that use Gradle Kotlin DSL ? 2) I must be missing something , but I cannot seem to find any Kotlin JS examples that work with latest Gradle (ok, found one: https://github.com/eggeral/kotlin-single-js-file-lib ) I could have completely missed something, but any current links would be appreciated. Thanks!
    m
    d
    • 3
    • 10
  • n

    Nikolai

    03/22/2019, 2:13 AM
    Hi, again I rad gradle documentation but still don't clearly understand how it works. When I create a very new project in IDEA as Mabile Android/iOS I got a project with multiple gradle connected files and directories. On project structure top where are two files : build.gradle, settings.gradle. settings.gradle is quite clear for me. But build.gradle is not :
    buildscript {
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.2.0'
        }
    }
    repositories {
        google()
        jcenter()
    }
    The main thing what I don't understand is purpose of 'buildscript' section, I mean why not put everything outside of this section? What is the difference between 'repositories' inside and outside 'buildscript' (btw where is another project included into parent 'app' and it have his own 'repositories' section inside his build.gradle file )?
    c
    n
    • 3
    • 4
  • e

    Erik Bylund

    03/26/2019, 11:13 PM
    Wondering if someone can give me some direction. I’ve got two functions: Im not sure how many subscriptions there will be and im trying not to load them all into memory. In php, there is a concept of a generator where you can iteratively return batches of data by using yield instead of return. The code that calls the generator can then just loop over the return value of the function and iteratively perform actions. Is there a nice way to do this in Kotlin? I thought maybe Sequences was the answer, but I may just be missing something.
    n
    • 2
    • 1
  • o

    oday

    03/27/2019, 12:02 PM
    regardless if too long for margin or not
    k
    • 2
    • 20
  • d

    davec

    03/29/2019, 4:38 PM
    I'd like to sort a List using a function reference looked up from a Map. If all function references returned the same type (
    String
    , for example) this would work fine. However in the case below where the return type is
    Any
    , it doesn't work.
    data class Foo(val name:String, val age:Int)        
            val sortModes = mapOf("name" to Foo::name, "age" to Foo::age)
            val myList = listOf(Foo("Dog", 17), Foo("Cat", 12), Foo("Mouse", 3))
            val sortFunc = sortModes["name"] ?: error("Not found") //  returns KProperty1<Foo, Any>
            println(myList.sortedWith(compareBy(sortFunc)) // <-- compiler error
    What magic is required to get Kotlin to sort by a function reference that can return
    Any
    ?
    h
    • 2
    • 7
  • m

    matt tighe

    03/29/2019, 9:13 PM
    is there a way to avoid this compiler error in a function that has a return type?
    acraWrapper.logAndThrow()
    logs some exception information and then just rethrows the exception outside of just tricking it by returning an invalid value, that is
    p
    k
    • 3
    • 17
  • t

    tipsy

    03/30/2019, 1:37 AM
    what is the kotlin equivalent of
    Map<Class, Object>
    ? intellij suggests both
    Map<Class<Any>, Any>
    and
    Map<Class<*>, Any>
    as parameter type, but neither work when calling the method from java
    d
    a
    • 3
    • 3
  • h

    Hexa

    03/31/2019, 12:48 AM
    Any know any cheat sheets/ best practices for optimising performance of applications written in Kotlin
    s
    • 2
    • 2
  • s

    Saurabh

    04/01/2019, 8:16 AM
    I have a single thread backed dispatcher to be used with coroutines. Could someone tell if the submitted coroutines will execute in order of submission or if they can be executed out of order.
    d
    • 2
    • 3
  • t

    todun

    04/01/2019, 8:27 AM
    @here kotlin noob trying to build a cross platform app for cafeteria management. Where would you recommend I start ?
    o
    j
    • 3
    • 13
  • o

    oday

    04/03/2019, 10:10 AM
    like I want to make an array out of all the
    objects.name
    from that list and use that array independently
    d
    • 2
    • 5
  • j

    JM Santos

    04/05/2019, 12:18 AM
    Hi guys, just wondering as I stumbled on the DSL. It looks great and gives me clarity. What's the best use case to use it? Just saw it here in action https://play.kotlinlang.org/byExample/09_Kotlin_JS/06_HtmlBuilder
    d
    • 2
    • 6
  • h

    hho

    04/05/2019, 8:16 AM
    AFAIK, Kotlin only generates bytecode for Java 6 or Java 8.
    n
    a
    • 3
    • 7
  • j

    jurajsolarml

    04/05/2019, 2:37 PM
    Hello, Can you help me? I have a question.I am beginner. I have to make a list of castles around 50km. How do I do this to be used API.
    k
    h
    m
    • 4
    • 11
  • u

    ursus

    04/06/2019, 3:35 AM
    private val typeface = Typeface.create(Typeface.DEFAULT_BOLD, Typeface.BOLD)
    
    class InitialsDrawable(val context: Context) : Drawable() {
        private val textPaint = Paint().apply {
            isAntiAlias = true
            color = context.getAttr(R.attr.defaultTextColor)
            textSize = context.resources.dpToPixels(11F)
            typeface = @file:typeface <--------------
            textAlign = Paint.Align.CENTER
        }
    s
    • 2
    • 3
  • m

    Mahi

    04/06/2019, 9:42 AM
    May I know if the type of result is inferred at Runtime ? If not, what is it called ? Here, Value of result is either "HelloString" or 2
    while (index < 3) {  
            index ++
    
            val result = cakesList?.let{ 
                     if(index == 2) {
                         "HelloString"
                     } else {
                      2   
                     }
                } 
    
            println("result value = $result")
    
            when(result) {
              is String -> println(" result variable is a String")
    
              is Int -> println(" result variable is Integer")
    }
    o
    s
    • 3
    • 4
  • s

    scottiedog45

    04/06/2019, 7:13 PM
    I’m in Android studio, and I would like a file in the left side file tree to open after a single click, not a double click. Where do I find this setting?
    m
    • 2
    • 1
  • s

    Smallville7123

    04/09/2019, 1:03 AM
    why do i get
    > java.lang.NullPointerException (no error message)
    for
    v[0]!!::class.objectInstance
    s
    k
    • 3
    • 17
  • s

    Smallville7123

    04/09/2019, 1:58 AM
    how do i obtain an instance of a class without specifying it explicitly
    fun ret() {
        class a {
            var empty: Int = 0
        }
    
        val f = arrayListOf<a>()
        f.add(a()) // class a is explicitly specified
    }
    s
    i
    • 3
    • 6
  • s

    Smallville7123

    04/09/2019, 4:06 AM
    Int is a primative type right? https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html https://kotlinlang.org/docs/tutorials/kotlin-for-py/primitive-data-types-and-their-limitations.html
    s
    • 2
    • 6
  • s

    Smallville7123

    04/09/2019, 5:14 AM
    if a type is passed as a paramater : Any, is its original type lost?
    s
    d
    • 3
    • 6
Powered by Linen
Title
s

Smallville7123

04/09/2019, 5:14 AM
if a type is passed as a paramater : Any, is its original type lost?
s

serebit

04/09/2019, 5:28 AM
This is an XY problem. Your approach is flawed. If you’re trying to double the length of a list, you can’t create a default value out of nowhere. Pass a default value to the function and use that, or pass a lambda that creates a default value
I’d also like to add that I don’t know why you’ve ignored suggestions to learn via the koans and have instead continued to hammer at this attempted solution which cannot work
We’re not here to teach you kotlin. There are resources you can use to learn, and we can point you towards those
s

Smallville7123

04/09/2019, 5:51 AM
so it is basically impossible to determine the original type of a variable that is passed as a parameter?
d

diesieben07

04/09/2019, 6:53 AM
Boxed and unboxed versions of
Int
are used interchangeably. When passed as
Any
it must be boxed. You can use https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/java-primitive-type.html to get the primitive java class from either boxed or unboxed.
s

Smallville7123

04/09/2019, 6:58 AM
ok
View count: 5