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
announcements
  • z

    zachtib

    02/17/2019, 10:10 PM
    Is there a good Kotlin example equivalent to this: http://f2prateek.com/2017/04/21/unwrapping-data-with-retrofit-2/ for a generic
    Envelope<T>
    response body adapter? The converter factory in this example uses the Java wildcard generic (
    *
    ) and I'm not sure how to adapt that to Kotlin
    d
    g
    • 3
    • 11
  • h

    Hexa

    02/18/2019, 8:43 AM
    Is there a way to run a single unit test via Intellij using https://github.com/kotlintest/kotlintest?
    t
    d
    s
    • 4
    • 14
  • t

    Tom Adam

    02/18/2019, 9:03 AM
    Hi guys, I was wondering what is the naming convension for files containing ‘multiple’ stuff - classes, extension functions, etc... So far we used lowercase naming for such things. Like functional.kt, builders.kt, etc.
    t
    s
    +3
    • 6
    • 6
  • g

    GarouDan

    02/18/2019, 1:06 PM
    Hi, can we respond to a unknown method call in Kotlin? For example, on the Rosetta Code we have a lot of options for different languages but the Kotlin version is using a javascript method only. https://rosettacode.org/wiki/Respond_to_an_unknown_method_call#Kotlin What I’m looking for is the
    method_missing
    of ruby, the
    __call__
    in PHP, and so on. I’ve heard about delegation in Kotlin, but I’m not so sure we can achieve the same result, for example, something like:
    MyClass().unknownMethod()
    // returns, for example, “You’ve called the `unknownMethod`“. Can someone give me an small example how can we achieve that? Thanks in advance
    c
    m
    r
    • 4
    • 14
  • r

    reik.schatz

    02/18/2019, 1:10 PM
    does this work with statically typed languages? I know Scala has something like
    Dynamic
    but this is not what you mean probably
    g
    j
    m
    • 4
    • 13
  • j

    Jeff Gulbronson

    02/18/2019, 1:38 PM
    Curious on people’s opinions for extension function best practices. In my mind, they’re good for extending classes you don’t have access to, either to add methods or make them null-safe, or want to extend in a very limited scope with private extension functions. One thing I noticed is sometimes I see people use variables from the scope the extension function is defined in, which feels weird to me. I tried to draft a “rule” of sorts for us to use at work, and was wondering how others feel extension functions should be used. (This is especially relevant as we use Guice everywhere in our server app)
    Extension functions should not use variables from a scope other than the scope available to them from the class they’re extending. Instead, variables should be passed in as parameters. Put another way, extension functions should be “stateless”, and not rely on where they’re defined to function. Extension functions should be able to be moved to a new file and continue to work.
    c
    s
    d
    • 4
    • 44
  • d

    Daniele Segato

    02/18/2019, 4:45 PM
    Do you know of any library that generate builder pattern for Java over a kotlin data class? I was using Immutables (https://immutables.github.io/) library in Java. Kotlin data classes are so much better but they aren't very comfortable to use from Java, specially if you have big constructors or many ways of creating the object. Thanks in advance (please answer in thread, i subscribed it)
    t
    c
    +3
    • 6
    • 22
  • s

    snowe

    02/18/2019, 6:35 PM
    Can anyone explain to me how to modify this to work in kotlin? There is no
    hasNext()
    method
    , so I cannot perform whether there is an end in the
    while
    .
    public static void printEachForward(BreakIterator boundary, String source) {
         int start = boundary.first();
         for (int end = boundary.next();
              end != BreakIterator.DONE;
              start = end, end = boundary.next()) {
              System.out.println(source.substring(start,end));
         }
     }
    ✔️ 1
    b
    • 2
    • 2
  • s

    snowe

    02/19/2019, 4:48 AM
    why does a non-local return from an inline function, have to be passed through in a lambda? e.g.
    returnFromInline { return }
        inline fun returnFromInline(ret: () -> Unit) {
                ret()
        }
    but not
    returnFromInline()
        inline fun returnFromInline() {
                return
        }
    s
    d
    s
    • 4
    • 10
  • k

    kassim

    02/19/2019, 10:27 AM
    the deprecated function with the 'not' signature is a great idea though I failed to give full context and unfortunately I need it for a generic of a generic full context: I'm trying to create a Kotlin property backed by a BehaviourRelay (an Rx observable object) and want to ensure obvious mutables aren't used
    class BehaviorRelayUpdateOnlyProperty<T>(relay: BehaviorRelay<T>) : BehaviorRelayProperty<T>(relay)
    I wanted to prevent T from extending MutableCollection - but with your solution the new constructor shares the same JVM signature as the original
    constructor(mutablePropertyRelay: BehaviorRelay<MutableCollection<*>>) : this(mutablePropertyRelay)
    isn't accepted
    k
    • 2
    • 1
  • t

    tapchicoma

    02/19/2019, 3:38 PM
    Why does this work:
    fun bar(): Single<List<Number>> {
        return Single.just(listOf<Int>())
    }
    But this doesn't (
    type mismatch
    ):
    fun bar(): Single<List<Number>> {
        val foo = Single.just(listOf<Int>())
        return foo
    }
    Removing
    Single
    or changing to:
    fun bar(): Single<List<Number>> {
        val foo = Single.just<List<Number>>(listOf<Int>())
        return foo
    }
    solves the issue 🤔
    s
    • 2
    • 3
  • j

    jbnizet

    02/19/2019, 3:50 PM
    Hello. Is there a way (contracts?), or will there ever be a way to do the following? - mark a function as side-effect-free, so that the compiler can warn if we call the function and do nothing with what it returns? - mark a class (I’m thinking of a JPA entity here) as only usable in a single thread, so that instance variables which have been checked as not null do not need to be used with
    ?.
    or
    !!
    Sorry if that has been asked before. It’s been a long time I haven’t been here 🙂
    k
    • 2
    • 3
  • z

    ziad

    02/19/2019, 9:27 PM
    Hi guys, are there any recommended frameworks that are production ready and suitable for implementing a socket based back-end for an indie game?
    h
    m
    • 3
    • 4
  • j

    jkbbwr

    02/20/2019, 2:09 AM
    Anyone know why all jetbrains projects are starting the terminal in a weird location
    g
    i
    • 3
    • 4
  • g

    Gustav

    02/20/2019, 6:28 AM
    I'm trying to build an API for a rule engine in Kotlin and I could really need some help to first of all figure out if what I want to do is at all possible. And secondary if it is how to modify my code to get it working.
    t
    • 2
    • 2
  • d

    davidasync

    02/20/2019, 7:12 AM
    Hello anybody know about
    fuel http client
    ? I dont know why fuel http header set the value as array of string instead of normal string for example
    {Origin=[abc], Content-Type=[application/json]
    instead of
    {Origin=abc, Content-Type=application/json
    is there any method to overide it to not use array of string?
    g
    s
    • 3
    • 10
  • d

    Davio

    02/20/2019, 7:41 AM
    I got a nasty NullPointerException because I didn't check the nullability of a return platform type (in my case
    String!
    ); is there an option to treat these platform types as nullable by default, meaning you have to consciously choose to deal with their possible nullability?
    ➕ 1
    g
    • 2
    • 3
  • j

    Jay

    02/20/2019, 9:11 AM
    Like
    interface MyInterface: T where T : SomeType
    ?
    p
    s
    • 3
    • 3
  • m

    marstran

    02/20/2019, 9:30 AM
    Please use threads :thread-please: 🙂
    ➕ 12
    k
    p
    +2
    • 5
    • 6
  • s

    spand

    02/20/2019, 1:53 PM
    Anyone else have problems with the compiler keeping kotlin/js files open ?
    s
    • 2
    • 3
  • l

    LeoColman

    02/20/2019, 2:39 PM
    Is there any alternative for
    lazy
    that includes the receiver? So that I can do
    val Foo.bar by lazy { this.baz }
    where
    this
    is
    Foo
    u
    s
    i
    • 4
    • 4
  • s

    snowe

    02/20/2019, 4:06 PM
    why is kotlin not inferring the Supplier properly? I’ve tried several ways, including anonymous function, casting null, plain declaration…
    t
    • 2
    • 8
  • a

    Andrew Gazelka

    02/20/2019, 5:40 PM
    I am running this code
    fun test1() {
        println("1")
        printId()
        thread {
            println("2")
            printId()
            throw IllegalStateException("an exception")
        }.join()
        println("3")
    }
    
    
    fun printId(){
        println("Thread ID: $id")
    }
    
    val id get() = Thread.currentThread().id
    and getting
    1
    Thread ID: 1
    2
    Thread ID: 11
    Exception in thread "Thread-0" java.lang.IllegalStateException: an exception
    	at com.github.andrewgazelka.kotlintest.ThreadExceptionTestKt$test1$1.invoke(ThreadExceptionTest.kt:12)
    	at com.github.andrewgazelka.kotlintest.ThreadExceptionTestKt$test1$1.invoke(ThreadExceptionTest.kt)
    	at kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30)
    3
    why
    Thread-0
    ?
    s
    • 2
    • 3
  • a

    Andrew Gazelka

    02/20/2019, 5:41 PM
    none of the running threads have an ID of 0
    s
    n
    d
    • 4
    • 8
  • m

    Micah Church

    02/21/2019, 3:42 AM
    The line implementation 'com.github.altavir:kmath:Tag' is giving me trouble, I have changed the tag to 0.0.2-dev-1 however that tag seems invalid
    g
    a
    • 3
    • 9
  • c

    christophsturm

    02/21/2019, 11:09 AM
    is there a method that converts a data class to a map? or iterates over all its fields?
    k
    h
    • 3
    • 5
  • g

    Gustavo Maciel

    02/21/2019, 11:10 AM
    When you access the map, it should contain all the data from the fields
    c
    • 2
    • 1
  • i

    Iaroslav Postovalov

    02/21/2019, 12:49 PM
    Hello. It seems that Kotlin 1.3.21 is not compatible with Gradle 4.10.3....
    s
    h
    e
    • 4
    • 3
  • m

    Martin Wangen

    02/21/2019, 12:58 PM
    Hi! Anybody know what i should replace this with? Or how to add default value = 0
    var harvest : HashMap<String,Int> = HashMap()
    harvest[plant.name] += amount
    s
    e
    +2
    • 5
    • 6
  • h

    Hexa

    02/21/2019, 2:54 PM
    is there difference any performance between declaring the
    logger
    in
    companion object
    or just declaring it outside the class like this
    private val logger = LoggerFactory.getLogger()
    class SomeKotlinClass{
    	//use logger here
    }
    ? which one is for best practice?
    l
    s
    • 3
    • 3
Powered by Linen
Title
h

Hexa

02/21/2019, 2:54 PM
is there difference any performance between declaring the
logger
in
companion object
or just declaring it outside the class like this
private val logger = LoggerFactory.getLogger()
class SomeKotlinClass{
	//use logger here
}
? which one is for best practice?
l

LeoColman

02/21/2019, 3:00 PM
Personally, I never try to analyze these kinds of functions performance-wise. It will never make that big of a difference
s

streetsofboston

02/21/2019, 3:00 PM
There is no real performance difference.
However, if you want your code more testable, I’d create a logger interface and use your favorite dependency injection method to provide an actual implementation.
View count: 3