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

    Florian

    10/04/2019, 7:43 PM
    I was under the impression that
    const val
    can not be assigned any function calls, but as I found out from this SO question it's actually possible for some functions: https://stackoverflow.com/questions/44921746/what-can-be-expressed-in-a-compile-time-constant-const-val From the given answers, it's not completely clear to me what is the reason for that. Is it because these function calls are not actually translated to function calls by the compiler, but replaced for operators?
    k
    • 2
    • 3
  • f

    Florian

    10/05/2019, 6:08 PM
    I don't have much experience in Kotlin, but doesn't the exception
    laneinit
    throws defeat the purpose of null safety?
    s
    p
    d
    • 4
    • 6
  • m

    Martin Nordholts

    10/06/2019, 6:24 AM
    Why is it necessary to have a
    Observer
    prefix in the second line below in order for SAM conversion to work, but not in the first line? The last parameter has identical declarations in these two cases.
    MutableLiveData<String>().observeForever({  })        // No 'Observer' prefix necessary
        MutableLiveData<String>().observe(this, Observer {  })        // 'Observer' prefix necessary!
    
        // Java declarations
        public void observeForever(@NonNull Observer<? super T> observer) {
        public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
    i
    • 2
    • 9
  • f

    Florian

    10/06/2019, 1:28 PM
    a clarification: file-level variables are not referred to as "global variables", right? They are properties
    d
    • 2
    • 8
  • f

    Florian

    10/06/2019, 3:32 PM
    can anything else be assigned to a
    const val
    besides literals and other `const val`s?
    d
    • 2
    • 2
  • t

    Tuang

    10/07/2019, 8:37 AM
    Is there any one who know how to append text file. I m making access log file. My code only write once to a file, how to append text?
    class AccessLog: Serializable {
        companion object {
            var LOG = "/usr/local/logs/access_log"
            @Synchronized
            fun write(domain: String, remoteIp: String, userId: Int) {
                File(LOG).bufferedWriter().use { out ->
                    out.write("""domain: $domain    remote_ip: $remoteIp    user_id: $userId    """)
                }
            }
        }
    d
    d
    • 3
    • 4
  • f

    Florian

    10/07/2019, 8:02 PM
    A
    const val
    1) optimizes the generated bytecode 2) can be used in annotations. My question: are there any other benefits over just using
    val
    that I am missing?
    k
    l
    • 3
    • 34
  • s

    Slackbot

    10/08/2019, 11:56 AM
    This message was deleted.
    k
    • 2
    • 1
  • u

    ursus

    10/09/2019, 7:17 PM
    Why does
    Foo : Bar<Quax>
    require
    Quax
    to be public, i.e. internal not allowed?
    d
    c
    +2
    • 5
    • 18
  • u

    ursus

    10/09/2019, 7:26 PM
    Foo is final, I dont get it
    r
    • 2
    • 22
  • v

    victor mazeli

    10/10/2019, 9:36 AM
    😀 Hello everyone am victor and am new to kotlin, a new resources or Tutorial to help a novice like me grow🤗
    👋 10
    m
    g
    +2
    • 5
    • 5
  • r

    raj

    10/10/2019, 6:38 PM
    FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':compileKotlin'.
    Kotlin could not find the required JDK tools in the Java installation '/usr/lib/jvm/java-8-openjdk-amd64/jre' used by Gradle. Make sure Gradle is running on a JDK, not JRE.
    * Try: Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0. Use '--warning-mode all' to show the individual deprecation warnings. See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warnings
    a
    • 2
    • 1
  • b

    Bacho Kurtanidze

    10/10/2019, 8:24 PM
    Hey, I'm relatively new to kotlin, for now its very smooth experience for me, but one thing that bothers me is that there is no package-private modifier, so does it mean that kotlin doesn't need it or its one of the downsides that should be fixed?
    l
    k
    m
    • 4
    • 4
  • f

    Florian

    10/10/2019, 8:57 PM
    I'm confused by this sentence in the docs:
    If a Kotlin file contains a single class (potentially with related top-level declarations), its name should be the same as the name of the class, with the .kt extension appended.
    Because IntelliJ/AS removes the
    .kt
    if the file contains only 1 class
    k
    • 2
    • 3
  • e

    Esa

    10/11/2019, 7:35 AM
    Hi folks, I’m working on a pretty standard spring boot / kotlin app, where we’ve an api written in kotlin and a frontend in react. We just did our first coroutines here, and I’ve some questions about it. The usecase was to optimize a very slow function, and we did that by adding 3
    CoroutineScope(EmptyCoroutineContext).async {}
    calls on the 3 slowest components of that function, and awaiting the results at the end, as well as optimizing the order of the calls. However, this means that function and every function up to the controller /endpoint now has a
    suspend
    qualifier, as well as the controller having a
    runBlocking {}
    wrapped around the function (it doesn’t seem like a major issue to me, that endpoint has about a 3.5s runtime now).. And as this is my first foray into coroutines, I’m sort of anxious there’s some drawbacks to this I’m missing.
    d
    a
    m
    • 4
    • 6
  • b

    Big Chungus

    10/12/2019, 10:54 AM
    Is there a way to check if lambda val bodies are the same? I've tried checking by hashCodes, but those are still different for identical lambdas
    b
    j
    +2
    • 5
    • 11
  • b

    Bacho Kurtanidze

    10/12/2019, 5:49 PM
    wouldnt it be better if defult access-modifier was internal rather than public? I think it would make our code more encapsulated
    🇳🇴 3
    n
    b
    +3
    • 6
    • 8
  • p

    Pablichjenkov

    10/13/2019, 11:35 PM
    I have below method in a companion object, which should extract a specific implementation class Wrapper depending on the Kotlin primitive type.
    fun extractRealClass(valueClass: Class<*>): Class<out PrimitiveWrapper<*>>? {
    
        return when (valueClass) {
            
            Boolean::class.java -> BooleanWrapper::class.java
            
            Int::class.java -> IntWrapper::class.java
    
            String::class.java -> StringWrapper::class.java
    
            else -> null
            
        }
    
    }
    
    // where PrimitiveWrapper is defined as:
    
    open class PrimitiveWrapper<T>(val value: T) {... Above func lives in this class companion}
    
    class BooleanWrapper(value: Boolean) : PrimitiveWrapper<Boolean>(value) { ... }
    
    class IntWrapper(value: Int) : PrimitiveWrapper<Int>(value) { ... }
    on another class
    Entry
    I have this:
    Entry<T: Any?>(
        private val key: String,
        private val clazz: Class<T>
    ) {
    
    override fun getInstance(): T? {
    
        // It always return null when calling above mentioned func.
        val primitiveClass: Class<out PrimitiveWrapper<*>>?
                    = PrimitiveWrapper.extractRealClass(clazz)
    
    }
    
    }
    Whenever I call the
    PrimitiveWrapper.extractClass(clazz)
    with the save class info it always return null. I tried many things and no matter what in the
    when
    block the coming class always print like
    int
    or
    <http://kotlin.Int|kotlin.Int>
    but never
    java.lang.Integer
    . Could some body shed some light?
    y
    • 2
    • 2
  • h

    harry.singh

    10/14/2019, 11:41 AM
    Hey guys! Wondering how does Kotlin allows access to members of private anonymous object in a class?
    e
    • 2
    • 3
  • f

    Florian

    10/14/2019, 8:56 PM
    I don't have to initialize a property right away if I use
    lateinit
    or override the
    getter
    . Any other ways to get around immediate initialization? (It's a theoretical question)
    n
    r
    y
    • 4
    • 13
  • s

    Sudhir Singh Khanger

    10/15/2019, 5:31 AM
    Kotlin has a
    Map/MutableMap
    which is a
    LinkedHashMap
    which preserves the insertion order unlike
    HashMap
    . In Java/Android, if one is used to using
    HashMap
    then I would think I can continue using
    Map/MutableMap
    in Kotlin. Is that correct?
    d
    k
    e
    • 4
    • 10
  • v

    veesus mikel heir

    10/15/2019, 11:33 AM
    Can delegating to an interface in a class override some of the functions and members that the actual base class of my class inherits
    • 1
    • 1
  • v

    veesus mikel heir

    10/15/2019, 4:05 PM
    i cant pass this out of the constructor
    c
    • 2
    • 1
  • e

    Ellen Spertus

    10/15/2019, 9:34 PM
    Where’s a good place for me to learn about
    Flow
    ? I have not used React so lack that background, although I am familiar with streams from functional programming and have experience with asynchronous callbacks.
    d
    p
    • 3
    • 4
  • f

    Florian

    10/16/2019, 2:07 PM
    do you consider the "class header" = name +
    class
    keyword + primary constructor or only the primary constructor? The Kotlin Docs use the latter definition (+ type parameters) but that's not what I have in mind
    k
    • 2
    • 2
  • s

    Sylvain Patenaude

    10/16/2019, 2:39 PM
    I created a Kotlin project with the template "Mobile Shared Library | Gradle", but I don't have the (expected?) gradle-wrapper.jar file in the gradle/wrapper folder. Is it only a question of project configuration? Thanks in advance.
    a
    a
    • 3
    • 6
  • m

    Michał Kalinowski

    10/16/2019, 4:16 PM
    hey can anyone tell me why when I try declare List of enums I get error
    No type arguments expected for class List
    l
    k
    • 3
    • 12
  • a

    Animesh Sahu

    10/16/2019, 4:41 PM
    I'm using ktor.io library. I want to know how to setup ping sending in websocket from client side to the server every interval defined in the server side. I tried to find docs but there weren't any examples of ping-pong. Somebody can help?
    s
    c
    • 3
    • 10
  • f

    Florian

    10/17/2019, 8:08 AM
    when I put an
    init
    block under a property I can initialize it there. This doesn't seem to work anymore if this property has a setter. Is that correct?
    a
    • 2
    • 4
  • m

    Martin Nordholts

    10/17/2019, 1:48 PM
    How can I get rid of
    !!
    in below code without getting compilation errors and without getting ugly code? Edit: And without recursion
    class Node(val child: Node?)
    
    fun Node.getLeaf(): Node {
        var candidate: Node = this
        while (candidate.child != null) {
            candidate = candidate.child!!
        }
        return candidate
    }
    t
    s
    w
    • 4
    • 5
Powered by Linen
Title
m

Martin Nordholts

10/17/2019, 1:48 PM
How can I get rid of
!!
in below code without getting compilation errors and without getting ugly code? Edit: And without recursion
class Node(val child: Node?)

fun Node.getLeaf(): Node {
    var candidate: Node = this
    while (candidate.child != null) {
        candidate = candidate.child!!
    }
    return candidate
}
t

thanksforallthefish

10/17/2019, 1:54 PM
tail recursion.
fun Node.getLeaf() : Node = findLeaf(this)

tailrec fun findLeaf(candidate: Node) {
  val child = candidate.child
  if(child == null) return candidate
  return findLeaf(child)
}
❤️ 1
👏 1
s

Svyatoslav Kuzmich [JB]

10/17/2019, 1:54 PM
while (true) {
        candidate = candidate.child ?: break
    }
☝️ 2
🤩 2
👍 2
m

Martin Nordholts

10/17/2019, 1:55 PM
Wow that is truly beatiful code 🤩 Thanks a lot!
w

wbertan

10/17/2019, 1:58 PM
tailrec fun Node.getLeaf(): Node = when (child) {
    null -> this
    else -> child.getLeaf()
}
My 2 cents 🙂
@Test
    fun asas() {
        val nodes =
            Node(
                0,
                Node(
                    1,
                    Node(2, null)
                )
            )
        assertEquals(Node(2, null), nodes.getLeaf())
    }
➕ 1
👍 3
t

thanksforallthefish

10/17/2019, 2:00 PM
cool did not think to use pattern matching (if you can call it so), that is still something I have to get used to coming from java (I guess java 12 would help). awesome!
View count: 5