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

    Paula Muldoon

    09/04/2020, 6:08 PM
    👋 super excited to be here! I’m a backend dev at BRYTER, where I started using Kotlin in March. Love the language so much!
    🎉 7
    👋 6
    s
    • 2
    • 1
  • t

    Thiago Nerys

    09/04/2020, 8:08 PM
    I'm documenting an api via swagger annotations. Is there any way to define an annotation in one point and reuse that wherever I need? Already tried to declare a
    @JvmStatic val response = @Annotation()
    but it doesn't work.
    c
    z
    • 3
    • 7
  • k

    khalil

    09/05/2020, 1:03 AM
    There is a way to declare a some list/array var and say that item type is
    T : X
    (type T that implements/extends a type X)?
    n
    • 2
    • 12
  • s

    Slackbot

    09/05/2020, 6:50 AM
    This message was deleted.
    a
    h
    • 3
    • 3
  • w

    Wesley Acheson

    09/05/2020, 8:47 AM
    I've got an class that is really a flattened representation of several different types of field. (its a document in nosql terms) that has lots of fields. (I think close to 100) and I'm building it up using a transformer, so on a field by field basis. I'm currently modeling as class where all fields are mutable, nullable, defaulting to null. However I know that certain values will always be eventually specified. Is that the right way to model this, Or should I have a data class with constructor parameters for everything? I feel that using a hundred myValue.copy(fieldName = fieldValue) may be a bad way to deal with it. Or I guess I could implement the builder pattern but that feels like an extra step to go wrong/maintain. Though I guess the advantage of the builder pattern Is that I can verify that the fields that aren't supposed to be null aren't null. What do you all think?#
    c
    • 2
    • 5
  • i

    ishitatsuyuki

    09/05/2020, 9:24 AM
    Does JetBrains automatically collect internal compiler errors related to incremental? Or do I need to report them when I encounter them? They happen once in a while but I can just get away with a rebuild so I currently just ignore them.
    a
    • 2
    • 1
  • b

    Burkhard

    09/05/2020, 2:14 PM
    Anyone here with experience writing JMH tests for kotlin? I'm trying to use https://github.com/melix/jmh-gradle-plugin but I get all sorts of strange errors. When I set
    kotlin.jvmTarget = "1.8"
    I get an error " Could not expand ZIP .../kotlin-stdlib-jdk7-1.4.0.jar". Also with jvmTarget 1.6 it still fails with "Error while instantiating tests: unable to set 'list' on Runner. This plugin version doesn't seem to be compatible with JMH 1.25."
    • 1
    • 1
  • j

    jean

    09/05/2020, 9:58 PM
    I have this simple sealed class :
    sealed class State {
        object Initial : State()
        object Loading : State()
        object Loaded : State()
    
        data class Error(val message: String) : State()
    }
    Now when I try to compile
    State::class.sealedSubclasses
    I get the error
    Unresolved reference: sealedSubclasses
    Do I need a special dependency for it?
    t
    • 2
    • 1
  • d

    df

    09/05/2020, 10:25 PM
    Hey there. What is the best co-routine way to process n batches in parallel? For each batch I need to make a remote call. It's okay if one of batches fails. Do I want to take a look into flows?
    z
    • 2
    • 2
  • m

    Mark

    09/06/2020, 3:36 AM
    I’m often faced with a choice between: 1. Adding a constructor argument that accepts a lambda 2. Making the class abstract and adding an abstract function Are there any clear advantages of one over the other? Note: the class does not otherwise need to be subclassed.
    n
    • 2
    • 5
  • f

    fkrauthan

    09/06/2020, 6:59 AM
    I am getting the error
    e: DBHealth.kt: (13, 22): Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6. Please specify proper '-jvm-target' option
    n
    • 2
    • 3
  • o

    Or Cohen

    09/06/2020, 8:47 AM
    Trying once again 🙏
    d
    • 2
    • 3
  • n

    Nikola Milovic

    09/06/2020, 2:19 PM
    Hey guys quick question, when solving this issue on LeetCode using Kotlin https://leetcode.com/problems/valid-perfect-square/ , I am encountering an issue related to Ints and Doubles and I cant seem to solve it. (the question itself is simple) So this is the Kotlin version (this doesnt, infinite loop)
    fun isPerfectSquare(num: Int): Boolean {
        var l = 1
        var r = num
    
        while (l <= r) {
            val mid: Long = (l + (r - l) / 2).toLong() 
            if (mid == num.toLong() / mid) { // here is where the problem is as 19/4 gives 4 instead of 4.75
                return true
            } else if (mid < num.toLong() / mid) { 
                l = mid.toInt() + 1
            } else {
                r = mid.toInt() - 1
            }
    
        }
    
        return false
    }
    And the Java version (this one works)
    public boolean isPerfectSquare(int num) {
            int low = 1, high = num;
            while (low <= high) {
                long mid = (low + high) >>> 1;
                if (mid * mid == num) {
                    return true;
                } else if (mid * mid < num) {
                    low = (int) mid + 1;
                } else {
                    high = (int) mid - 1;
                }
            }
            return false;
        }
    Basically the issue is, how to keep the floating precision in this example? I've encountered this problem a couple of times now. Try the Kotlin solution with 19 as input Thanks!
    e
    p
    • 3
    • 5
  • q

    Quantum64

    09/06/2020, 8:01 PM
    is there an official kotlin IR specification?
    e
    e
    • 3
    • 2
  • p

    PHaroZ

    09/07/2020, 1:01 PM
    Hi, I just discover contracts and try to play with it and a functor. Can you confirm that, as is, there is no way to achieve the above logic ?
    data class ValueHolder<A> (val value: A){
    	@OptIn(ExperimentalContracts::class)
    	inline fun <reified B : A> valueIs(): Boolean {
    		contract {
    			returns(true) implies (this@ValueHolder is ValueHolder<B>) // <- compiler error here "Cannot check for instance of erased type: ValueHolder<B>"
    		}
    		return value is B
    	}
    }
    the goal is to use
    #valueIs
    in a when statement and benefit of smart-casting in branch as
    when {
    	valueHolder.valueIs<TypeA> -> doStuffWithAHolder(valueHolder)
    	valueHolder.valueIs<TypeB> -> doStuffWithBHolder(valueHolder)
    }
    m
    d
    • 3
    • 10
  • a

    Ale

    09/07/2020, 7:58 PM
    I'm retrieving a list of documentSnapshot from Firestore, coverted to POJOs:
    private fun extractLevels(querySnapshot: QuerySnapshot): List<Level?> {
        return querySnapshot.documents
            .map { it.toObject(Level::class.java) }
    }
    If the list of documents is empty, this should just return an empty list, right? There shouldn't be nulls in the list. However, unless I set the return type as List<Level?>), I get an error because it's actually expecting that. What am I doing wrong, and how can I have this return a List<Level> ?
    t
    • 2
    • 3
  • c

    CLOVIS

    09/07/2020, 9:48 PM
    I don't see a channel to discuss the skiko project... I'm curious as to what the current state is, where can I get information on that?
    ❓ 1
    b
    • 2
    • 3
  • a

    Andrew Gazelka

    09/07/2020, 11:53 PM
    General question: Suppose I have a
    PriorityQueue
    , where each value
    V
    is sorted by according to a calculated
    priority: K = calc(V, otherStuff)
    . I want to be able to remove and add
    V
    to this priority queue based on equality. Should I 1. Have a
    Map<V,K>
    that the priority queue references in the sorting function and store the raw
    V
    in the priority queue 2. Use something like
    NodeEqValue<K,V>
    that has overridden equality for
    V
    3. Implemented some custom collection like
    TreeMap
    but that allows multiple equivalent keys 4. Add custom remove (probably the best)
    n
    b
    • 3
    • 4
  • r

    rrva

    09/08/2020, 10:24 AM
    are there some issues when calling functions with reified type parameters in multiple steps where type information is lost ?
    foo<T>()
    
    inline fun <reified T> foo(): T? {
        return bar<T>()
    }
    
    inline fun <reified T> bar(): T? {
        return objectMapper.readValue<T>(x)
    }
    Something like the above
    t
    • 2
    • 2
  • t

    tim

    09/08/2020, 3:12 PM
    Hi all, are there any recommended libraries for working with Geo data? The features I'm looking for are representations of locations as points (lat lng), polygons, etc, determining if one is inside another, and eventually working with addresses an converting them to from those basic points. This is multi platform as well so not limited to android.
    m
    f
    • 3
    • 17
  • n

    Nir

    09/08/2020, 3:45 PM
    Is there a good explanation somewhere of why
    Map
    does not inherit from
    Collection
    ?
    z
    s
    f
    • 4
    • 74
  • v

    vinny2020

    09/08/2020, 5:02 PM
    do you have to create your own custom sequence in order to make a range on a custom object?
    n
    • 2
    • 3
  • s

    Slackbot

    09/08/2020, 5:42 PM
    This message was deleted.
    👎 16
    👮‍♀️ 3
    🚓 4
    l
    b
    +2
    • 5
    • 4
  • j

    jojo.lichtenberger

    09/08/2020, 6:44 PM
    class XmlSessionDBCollection(
        private val ctx: RoutingContext,
        private val dbCollection: TemporalNodeCollection<AbstractTemporalNode<XmlDBNode>>, AutoCloseable,
        private val user: User
    ) : TemporalNodeCollection<AbstractTemporalNode<XmlDBNode>>, AutoCloseable by dbCollection {
    s
    e
    • 3
    • 11
  • s

    Steve

    09/08/2020, 8:26 PM
    How would I check the value of a MutableLiveData<Boolean> and if it's null, default it to false?
    a
    i
    • 3
    • 2
  • t

    TwoClocks

    09/09/2020, 1:15 AM
    why isn't inline on tailrec functions supported? It seems like a kinda obvious thing to add, as if you want to be more FP you'd use more tailrec fun's than while() loops.
    n
    r
    +2
    • 5
    • 17
  • b

    Bilel El Oud

    09/09/2020, 8:01 AM
    with kotlin i can develop mobile app (native and Cross plateform) ?
    s
    • 2
    • 4
  • c

    CLOVIS

    09/09/2020, 9:50 AM
    How can I write “this function accepts a parameter that should implement both Comparable and Serializable” (or any other two interfaces). I know I can define a generic as
    <T: out Comparable>
    to get the first one, but I don't see how to have two constraints.
    j
    • 2
    • 2
  • n

    npayyappilly

    09/09/2020, 11:07 AM
    How can I resolve
    GSON
    format conversion -
    Integer
    becomes
    Double
    Type ?
    m
    l
    • 3
    • 2
  • n

    Nir

    09/09/2020, 2:09 PM
    Didn't have luck with this yesterday in #getting-started , thought I'd try here to get more eyes on it: So, I started toy projects in intellij by creating the regular kotlin application. That was fine, but there was no gradle file that I could find so when I wanted to add dependencies to play around with (arrow), I couldn't figure out how to do it. So then I started a new project, and I picked a gradle project (with the build.gradle.kts file) Now, I can see where to add dependencies, but I can't actually build and run main When I try, I get "Error: Could not find or load main class MainKt". Do I need to add targets to the gradle file? I have sourceSets already...
    import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
    
    plugins {
        kotlin("jvm") version "1.4.0"
        kotlin("kapt") version "1.4.0"
    }
    
    group = "FooBarBaz"
    version = "1.0-SNAPSHOT"
    
    
    
    repositories {
        mavenCentral()
        jcenter()
        maven ("<https://dl.bintray.com/arrow-kt/arrow-kt/>" )
    }
    
    val arrow_version = "0.10.5"
    
    dependencies {
        implementation(kotlin("stdlib-jdk8"))
        implementation(kotlin("io.arrow-kt:arrow-optics:$arrow_version"))
        implementation(kotlin("io.arrow-kt:arrow-syntax:$arrow_version"))
        implementation(kotlin("io.arrow-kt:arrow-optics:$arrow_version"))
        //kapt("io.arrow-kt:arrow-meta:$arrow_version")
    }
    
    tasks.withType<KotlinCompile> {
        kotlinOptions.jvmTarget = "1.8"
    }
    sourceSets.main {
        java.srcDirs("src/main/java", "src/main/kotlin")
    }
    My hello world file is in 
    src/main/kotlin/main.kt
    e
    n
    • 3
    • 23
Powered by Linen
Title
n

Nir

09/09/2020, 2:09 PM
Didn't have luck with this yesterday in #getting-started , thought I'd try here to get more eyes on it: So, I started toy projects in intellij by creating the regular kotlin application. That was fine, but there was no gradle file that I could find so when I wanted to add dependencies to play around with (arrow), I couldn't figure out how to do it. So then I started a new project, and I picked a gradle project (with the build.gradle.kts file) Now, I can see where to add dependencies, but I can't actually build and run main When I try, I get "Error: Could not find or load main class MainKt". Do I need to add targets to the gradle file? I have sourceSets already...
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    kotlin("jvm") version "1.4.0"
    kotlin("kapt") version "1.4.0"
}

group = "FooBarBaz"
version = "1.0-SNAPSHOT"



repositories {
    mavenCentral()
    jcenter()
    maven ("<https://dl.bintray.com/arrow-kt/arrow-kt/>" )
}

val arrow_version = "0.10.5"

dependencies {
    implementation(kotlin("stdlib-jdk8"))
    implementation(kotlin("io.arrow-kt:arrow-optics:$arrow_version"))
    implementation(kotlin("io.arrow-kt:arrow-syntax:$arrow_version"))
    implementation(kotlin("io.arrow-kt:arrow-optics:$arrow_version"))
    //kapt("io.arrow-kt:arrow-meta:$arrow_version")
}

tasks.withType<KotlinCompile> {
    kotlinOptions.jvmTarget = "1.8"
}
sourceSets.main {
    java.srcDirs("src/main/java", "src/main/kotlin")
}
My hello world file is in 
src/main/kotlin/main.kt
e

ephemient

09/09/2020, 2:33 PM
this looks like it sets up a java library module
what are you running?
n

Nir

09/09/2020, 2:39 PM
what do you mean by "what am I running" ?
I also tried to setup a new gradle project, btw. And then it immediately fails once the project is created, to sync gradle. I have a red message "Unable to get Gradle home directory", and another error "Protocol message contained an invalid tag (zero)"
e

ephemient

09/09/2020, 2:48 PM
if you had
plugins {
    application
}
application {
    mainClassName = "MainKt"
}
then you could run
./gradlew run
, for example
I don't see where how you're trying to execute main
or do you not have a gradle wrapper set up??
n

Nir

09/09/2020, 2:52 PM
I'm only executing things via the IDE
I hit the little "play" button beside main
e

ephemient

09/09/2020, 2:54 PM
never did like IDEs… vim and command line all the way
but check the configuration
there should be something in the UI saying "use classpath of module" and "before launch: build"
n

Nir

09/09/2020, 2:57 PM
I don't see anything like that
e

ephemient

09/09/2020, 2:58 PM
just to check, you do have gradle wrapper set up, right?
n

Nir

09/09/2020, 3:10 PM
I'm not sure
I literally just created a new gradle project in the IDE
and then edited the build.gradle.kts file mostly from there
I'm honestly confused, why this is so hard to setup a working project from an IDE, for a language coming from an IDE company
When I create a new project as well, the gradle version is 4.10.3 by default, which is too old to work with this version of kotlin?!? So i have to change something to make it work...
had to feed the path to gradle 6.6.1 in the gradle-wrapper.properties
n

nanodeath

09/09/2020, 3:36 PM
I created a new Kotlin Gradle project this weekend and it defaulted to Gradle 6.4 I think. you're running the latest IntelliJ?
n

Nir

09/09/2020, 4:27 PM
Yeah I upgraded intellij, I thought I already had
I hope that helps with some of these things
View count: 4