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

    Marc Knaup

    12/06/2018, 5:52 PM
    java.lang.ClassCastException: service.CityName cannot be cast to java.lang.String
    in Kotlin 1.3.10 with inline classes. I heard this is resolved but that Kotlin update isn't released yet. When will it be released? Or can I use the dev build with Gradle somehow? 🙂
    k
    • 2
    • 3
  • m

    Marc Knaup

    12/06/2018, 6:59 PM
    no, I don't use String anywhere
    m
    • 2
    • 4
  • m

    Marc Knaup

    12/06/2018, 7:15 PM
    So assigning an
    inline class
    instance returned by a generic (
    reified
    ) function directly to a variable captured by a lambda seems to be problematic.
    o
    m
    • 3
    • 2
  • c

    crummy

    12/06/2018, 10:04 PM
    I want to declare a list that holds KClasses that extend Event, something like this:
    List<KClass<? extends Event>>
    I can't figure out what the right syntax for this is though, can someone help?
    p
    • 2
    • 3
  • c

    crummy

    12/07/2018, 12:23 AM
    Still wrestling with generics. Is it possible to do this simple event handler?
    class EventManager{
        private val listeners: MutableMap<KClass<out Event>, MutableList<EventListener<in Event>>> = HashMap()
    
        fun <T : Event> register(event: KClass<out T>, listener: EventListener<T>) {
            val eventListeners: MutableList<EventListener<T>> = listeners.getOrPut(event) { ArrayList() }
            eventListeners.add(listener)
        }
    
        fun notify(event: Event) {
            listeners[event::class]?.forEach { it.handle(event) }
        }
    }
    My
    getOrPut
    call wants a
    MutableList<EventListener<T>>
    but found
    MutableList<EventListener<in Event>>
    instead.
    p
    • 2
    • 3
  • c

    chansek

    12/07/2018, 9:34 AM
    listOf(1, 2, 3).slice(0..5) Instead of getting an ArrayIndexOutOfBoundxException, how can I get (1, 2, 3)
    d
    r
    a
    • 4
    • 4
  • r

    rocketraman

    12/07/2018, 3:55 PM
    Is changing a
    public fun
    to
    public inline fun
    binary and source compatible?
    i
    k
    • 3
    • 7
  • c

    Casey Brooks

    12/07/2018, 4:00 PM
    It should be source-compatible as long as only Kotlin is calling it. But it won’t be binary-compatible, as the method signature will only exist in the source. The compiler literally just replaces the method call with the body of the method, and leaves no trace of the original method.
    🇳🇴 1
    r
    • 2
    • 2
  • g

    Gokhan Alıcı

    12/07/2018, 5:28 PM
    I am trying to make simple json parser which will use jsonObject and JsonArray but firstly I need to create classes instance genericly
    a
    • 2
    • 2
  • k

    karelpeeters

    12/07/2018, 5:40 PM
    You need to look at the constructors via reflection.
    g
    d
    • 3
    • 10
  • t

    Travis Griggs

    12/07/2018, 7:14 PM
    Coming from Python/Smalltalk backgrounds, I really like explicit self receivers. Kotlin allows me to continue to be explicit (optionally) using
    this
    . For the grins of it (because sometimes silly ideas lead to better understanding), I thought I’d try something like this:
    val <Receiver>Receiver.self: Receiver get() = this
    It works pretty well. I can now use
    self
    in lieu of
    this
    . Except in a few cases. One such case is in an
    init
    block: private val manager:DownloadManager init { self.manager = self.context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager } It will not allow the
    self.manager
    reference there. It’s OK with the
    self.context...
    . And I can use just
    manager
    or
    this.manager
    , but for some reason my “selfish substitution” does not work there. Enlighten me?
    d
    a
    +2
    • 5
    • 18
  • w

    william

    12/08/2018, 4:22 PM
    in kotlin is it more idiomatic to define a var* with a custom getter and setter for persisting a value or defining methods for both to be explicit about the persistence going on
    a
    d
    • 3
    • 11
  • b

    benleggiero

    12/08/2018, 6:08 PM
    My Kotlin compiler is still crashing... I was hoping this would be sorted out after 1.0, but it's well into 1.3 now with no sign of stability. Is there ever going to be a stability release?
    n
    g
    • 3
    • 17
  • s

    sp33dy

    12/08/2018, 6:38 PM
    Good evening. Is there anyone out there using Eclipse, Kotlin and Gradle? I'm trying to find a way to get the Gradle Plugin to reference two Projects. Is it possible? I've googled and followed a LOT of articles, but keep hitting brick walls
    n
    • 2
    • 2
  • k

    keturn

    12/08/2018, 10:13 PM
    Oops. I just tried to define a function like this:
    fun isBetween(x, edge1, edge2): Boolean = x in (edge1 .. edge2)
    but that doesn't Do What I Mean because
    5 in (10 .. 1)
    is false. Is there anything in the standard library that handles this already, or do I have to add an
    if edge2 < edge1
    in there to make sure they're the right way around?
    d
    a
    g
    • 4
    • 20
  • d

    DJ2

    12/08/2018, 11:05 PM
    Quick quesiton, so
    findViewById
    is no longer necessary,
    val btnSaveClick= findViewById<Button>(R.id.btnSave)
          btnSaveClick?.setOnClickListener {
              Toast.makeText(this@ArticleAdapter, "Article saved.", Toast.LENGTH_LONG).show()
          }
    What should be used instead
    k
    • 2
    • 5
  • d

    Dico

    12/09/2018, 12:28 AM
    Is there a way to enable unsigned types module wide? To avoid having to put @UseExperimental on everything.
    t
    • 2
    • 3
  • k

    kenji_otsuka

    12/09/2018, 8:46 AM
    Hello, I want to use NonNull/Nullable annotations for Java code, but I heard that javax.annotation.NonNull/Nullable will be removed in the future. Then, which NonNull/Nullable annotation is recommended?
    g
    • 2
    • 1
  • k

    karelpeeters

    12/09/2018, 9:25 AM
    You want to implement
    V
    , an type not known at compile time?
    r
    a
    • 3
    • 5
  • p

    Pere Casafont

    12/09/2018, 10:51 AM
    hi there, what is the best way to solve that problem?:
    open class ParentFoo
    class ChildFoo : ParentFoo()
    
    abstract class ParentBar {
    	open var foo: ParentFoo? = null
    }
    class ChildBar : ParentBar() {
    	override var foo: ChildFoo?
    		get() = super.foo as ChildFoo?
    		set(value) {
    			super.foo = value
    		}
    }
    right now I'm not allowed to set
    ChildFoo
    as the `ChildBar`'s
    foo
    property type as it is not exactly the same type as its parent's
    foo
    , but as it doesn't have a backing field I think this should be able to compile without any problem. What am I missing there?
    p
    • 2
    • 5
  • k

    kef

    12/10/2018, 12:05 AM
    In the last AoC challenge you have to put marbles in a circle (linked list), sometimes moving back 7 places from the current position. Stripped version of the my code for that is below. I thought that the straight forward
    current.prev.prev.prev.prev.prev.prev.prev
    should be the fastest way possible, but out of curiosity I also did it as
    generateSequence(current) { it.prev }.take(8).last()
    and to my surprise, when I measured times of execution I got this : -
    .prev
    chain -> 2389ms -
    generateSequence
    -> 460ms So why is
    generateSequence
    5 times faster? On my machine I get results like that when looping up to 10mln, after that
    generateSequence
    suddenly takes 3s to finish.
    -.kt
    t
    k
    • 3
    • 5
  • v

    vngantk

    12/10/2018, 2:40 AM
    Is there a way I can disable synthetic property extensions generated for getter methods of java classes? I want to define my property extension having a name conflicting with the original getter method of the java class.
    g
    • 2
    • 5
  • e

    edwardwongtl

    12/10/2018, 9:51 AM
    What type should I be putting in
    ???
    such that
    toResult
    won’t error? I’ve tried
    Nothing
    and it is not working
    sealed class ApiResult<T>
    
    data class Success<T>(
        val msg: String,
        val data: T
    ) : ApiResult<T>()
    
    data class Failure(
        val error: String,
        val errMsg: String
    ) : ApiResult<???>()
    
    fun toResult(): ApiResult<User> {
            return if (error == "0") Success(
                msg = msg, data = movies
            ) else Failure(error = error, errMsg = errMsg)
        }
    k
    m
    d
    • 4
    • 8
  • m

    mc

    12/10/2018, 2:17 PM
    Is there a function akin to
    uncurry
    in kotlin? That is, a function which takes a function of two arguments and returns a function which takes a single pair of arguments?
    g
    a
    +2
    • 5
    • 7
  • l

    locke

    12/10/2018, 5:19 PM
    Is it possible to create a static extension function to a Java class? It doesn't have a Companion to attach it to, but the non-static version is genericized?
    s
    k
    g
    • 4
    • 28
  • s

    starke

    12/10/2018, 10:21 PM
    yeah maybe…but in that case
    putAll
    and
    put
    have that same uncertainty
    ☝️ 1
    r
    • 2
    • 2
  • x

    xenoterracide

    12/10/2018, 10:34 PM
    is their syntactic sugar around
    if (a != null && b != null ) {
    like there is with
    a?.let {
    ?
    d
    • 2
    • 4
  • x

    xenoterracide

    12/10/2018, 10:34 PM
    also, does kotlin have Traits
    d
    • 2
    • 2
  • r

    Robert Maguire

    12/10/2018, 10:37 PM
    Say I have a method A that returns a boolean, and a second method B that returns a nullable object. Is there a way with contracts that I can have it so if method A returns true, method B is known to be not null?
    r
    • 2
    • 1
  • w

    wck

    12/10/2018, 11:20 PM
    Hi, I have a silly question. Can a list of non-null type ever be possible to contain null value somehow?
    d
    b
    g
    • 4
    • 36
Powered by Linen
Title
w

wck

12/10/2018, 11:20 PM
Hi, I have a silly question. Can a list of non-null type ever be possible to contain null value somehow?
d

diesieben07

12/10/2018, 11:21 PM
In a Java environment, certainly.
You will get a descriptive exception thrown when accessing the list from Kotlin though
w

wck

12/10/2018, 11:22 PM
can you please give an example? thanks
d

diesieben07

12/10/2018, 11:24 PM
Java code:
class Evil {
  public static void beEvil(List<String> list) {
    list.add(null);
  }
}
In Kotlin:
fun main() {
    val list = mutableListOf<String>()
    Evil.beEvil(list)
    println(list[0]) // throws an exception
}
w

wck

12/10/2018, 11:27 PM
yeah, I’m indeed using Kotlin + Java. The example definitely make senes but the NPE from a non-null type list is certainly from Kotlin code only.
Thus I’m super confused…
d

diesieben07

12/10/2018, 11:28 PM
Yes, Java has no non-null types, hence there is no way for Java code to throw
w

wck

12/10/2018, 11:31 PM
I think my question should be . In Kotlin environment, I’m seeing NPE from iterating non-null list.
d

diesieben07

12/10/2018, 11:32 PM
Then some Java code put null into the list.
From the Kotlin side you must ensure that you don't pass a non-null list where Java might add a null.
w

wck

12/10/2018, 11:36 PM
umm…it’s unlikely Java code. Could it ever be Kotlin?
I checked, no Java code is modifying that list, very weird
b

Bernhard

12/10/2018, 11:46 PM
do you use the JVM stdlib?
w

wck

12/10/2018, 11:47 PM
it’s on Android, so I guess yes?
b

Bernhard

12/10/2018, 11:47 PM
my guess is that the NPE is thrown from Java code that is probably related to the implementation that you use
next guess would be concurrency
race condition
w

wck

12/10/2018, 11:49 PM
NPE is actually from Kotlin code. And how can concurrency inject null value into non-null list?
b

Bernhard

12/10/2018, 11:49 PM
it depends on how well the abstraction holds
and if things are atomic
do you have a stack strace btw?
w

wck

12/10/2018, 11:51 PM
my issue is almost same as this one
https://stackoverflow.com/questions/53015361/non-null-value-in-kotlin-produces-nullpointerexception
b

Bernhard

12/10/2018, 11:52 PM
that uses an ArrayList which is jvm
afaik
ok, could be both
@SinceKotlin("1.1") public actual typealias ArrayList<E> = java.util.ArrayList<E>
ok, so the built in ArrayList is just an alias for the jvm one
can you try to use a thread safe array list
https://stackoverflow.com/a/2444195
check if that fixes it. if it does it's a concurrency issue
w

wck

12/10/2018, 11:59 PM
yeah, guess this is the only thing I can do
b

Bernhard

12/11/2018, 12:00 AM
my guess is some jvm code is modifying your list in whatever way
or it's really an android/jvm bug which I doubt
w

wck

12/11/2018, 12:03 AM
yeah, I’m more leaning towards concurrency issue too. Very hard to reproduce it.
g

gildor

12/11/2018, 12:44 AM
One more dirty workaround consider list values as nullable if this possible for your code, but it may hide real bug in some cases
View count: 3