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

    Joan Colmenero

    03/23/2020, 3:31 PM
    Is there any way to use this
    sealed class
    to use it as a parent?
    sealed class ClientName {
        data class normalClass(val name: String) : ClientName()
        object SpecificObject : ClientName()
        object AnotherObject : ClientName()
    }
    So now, I need to have the same objects and class but different output, so on my extension function : That is something like this :
    fun ClientName.toText(): String = when (this) {
        is ClientName.SpecificObject -> "Print1"
        is ClientName.AnotherObject -> "Print2"
        is ClientName.normalClass -> if (this.name == "") "hello" else "Bye"
    }
    So now I see that I'd need different types, it means that
    SpecificObject
    ,
    AnotherObject
    and
    normalClass
    are goinna print different things depends of the type, so what I thought is create another
    sealed class
    like :
    sealed class Type1 : ClientName()
    sealed class Type2 : ClientName()
    And then in that extension
    toText
    check if is
    Type1
    then do X and if it's
    Type2
    do Y. But I do not know how to do it to get the same values and same clases as the
    ClientName
    what I'm missing?
    s
    t
    d
    • 4
    • 14
  • j

    jimn

    03/23/2020, 5:10 PM
    if (seekTo in (window1.first..(window1.second - rowsize)))
    does this compile to something other than
    it >  min and it < max
    ??
    a
    • 2
    • 1
  • s

    Stephan Schroeder

    03/23/2020, 6:25 PM
    I was waiting for news on Kotlin inline classes in Kotlin 1.4, but nothing in the blog post 😥
    ➕ 3
    l
    • 2
    • 2
  • k

    koral

    03/23/2020, 9:17 PM
    I have a code like this: https://pl.kotl.in/5vZUgXStV I expect that it will print
    true
    . However,
    ClassCastException: java.lang.Long cannot be cast to DogId
    is thrown. Is it a bug in kotlin? Or maybe I’m using inline classes incorrectly?
    j
    • 2
    • 2
  • j

    J6ey

    03/23/2020, 11:48 PM
    how do I use Kotlin to kill the coronavirus?
    😂 2
    s
    • 2
    • 1
  • t

    Travis Griggs

    03/23/2020, 11:56 PM
    Tired of having to annotate a bunch of methods with
    @ExperimentalStdlibApi
    to a bunch of methods, I changed my Kotlin Compiler Preferences in AndroidStudio to include
    -Xopt-in=kotlin.ExperimentalStdlibApi
    in the “Additional command line parameters” (as per the instructions here: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-experimental-stdlib-api/). However, I’m still getting build failures when I remove the annotations and depend on the global command line parameter. What am I not getting?
    i
    • 2
    • 1
  • c

    Chills

    03/24/2020, 9:41 AM
    im planning to give up my handler (account) [ kotlinlang] to someone , am i allowed to do that?
    l
    d
    t
    • 4
    • 7
  • t

    thana

    03/24/2020, 1:53 PM
    any idea why
    tasks.withType<KotlinCompile> {
        kotlinOptions {
            freeCompilerArgs += "-Xjsr305=strict"
            freeCompilerArgs += "-Xopt-in=kotlinx.serialization.ImplicitReflectionSerializer"
            jvmTarget = "1.8"
        }
    }
    results in
    w: Flag is not supported by this version of the compiler: -Xopt=in=kotlinx.serialization.ImplicitReflectionSerializer
    ? (kotlin 1.3.61)
    m
    i
    • 3
    • 6
  • d

    Dougrinch

    03/24/2020, 2:53 PM
    Hi! Can anyone explain why this code doesn't work?
    typealias F<T> = (T) -> T
    
    fun test() {
      val id: F<*> = { it }
      consume(id)//error here
    }
    
    fun <T> consume(v: F<T>) {
    }
    It looks like all should be fine, but the compiler tells me
    Type mismatch: inferred type is Any? but CapturedType(*) was expected
    . I thought that the star means "some unknown T", am I wrong?
    s
    • 2
    • 10
  • l

    LastExceed

    03/24/2020, 3:18 PM
    I wrote a library that I'd like to make publicly available, so people can easily use it with gradle/maven/ect. However I am completely lost with what i need to do now. I looked into MavenCentral/JCenter/Bintray but they all seem to assume that I am part of some organization, which I'm not. I also don't have a website so I don't even know what I should use as my "group id". can someone help me get started?
    t
    z
    • 3
    • 4
  • g

    Gilberto Diaz

    03/24/2020, 3:23 PM
    too many channels about testing. which one is the general channel about testing not related to a framework?
    t
    • 2
    • 1
  • c

    Chills

    03/24/2020, 4:02 PM
    we have decided to use kotlin for our startup for mobile. is anyone using it production? for some time. we have used Xamarin (F#) before
    s
    e
    z
    • 4
    • 5
  • g

    Gilberto Diaz

    03/24/2020, 5:01 PM
    I have question about cli app development. I created the #clikt channel for questions about that particular framework. I don’t see any general cli app development. If there is a channel about that please let me know
    z
    • 2
    • 4
  • s

    simtse

    03/24/2020, 7:27 PM
    I need a little help with understanding if multi-threading might be causing me some problems with this class. Here is an example:
    @javax.inject.Singleton
    class SpecificWork @Inject constructor() {
    
      private var cruncher: Cruncher? = null
    
      @GuardedBy("this")
      init {
        initCruncher()
      }
    
      @Synchronized
      private initCruncher() {
        // io work initialization
        cruncher = try {
          IOCruncher.init()
        } catch (e: IOException) {
          null
        }
      }
    
      fun doWork(): Result? {
        if (cruncher == null) {
          return null
        }
    
        // do work
        return Result("done")
      }
    }
    This
    SpecificWorker
    is provided via Dagger for dependency injection, but there could be many threads calling into it at the same time. I’m wondering • Is there a case where the
    doWork()
    started executing before the
    initCruncher()
    was able to assign the
    cruncher
    ? Making the
    cuncher
    null and failing early?
    t
    • 2
    • 4
  • a

    am414

    03/24/2020, 8:42 PM
    how to convert this MainList [ obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8, obj9, obj10 ] TO [ obj1 , obj2 , obj3 ] [ obj4 , obj5 , obj6 ] [ obj7 , obj8 , obj9 ] [ obj10 ] anyone understand me ??
    s
    i
    • 3
    • 3
  • s

    Serhiy Fedusov

    03/25/2020, 7:48 AM
    Hello. Can anyone explain to me, why some simle functions on Iterable return list and not Iterable subtype it was applied to? For example:
    inline fun <T> Iterable<T>.filter(
        predicate: (T) -> Boolean
    ) : List<T>
    If I chain multiple functions, say, using Set, it is simetimes uncomfortable to call
    toSet()
    each time the list is returned.
    l
    r
    • 3
    • 6
  • c

    corneil

    03/25/2020, 8:03 AM
    Does anyone have an answer for Heinz? https://twitter.com/heinzkabutz/status/1242722285712216064?s=20
    b
    • 2
    • 1
  • c

    christophsturm

    03/25/2020, 11:34 AM
    is there library that pretty prints java or kotlin objects via reflection? something like http://www.lihaoyi.com/PPrint/
    n
    m
    +2
    • 5
    • 12
  • s

    SrSouza

    03/25/2020, 3:16 PM
    Hi guys, why this happens? And what is the right way to fix it?
    d
    m
    l
    • 4
    • 4
  • e

    Edoardo Luppi

    03/25/2020, 5:03 PM
    How does the
    language-version
    compiler option works? Does it modify the outputted bytecode & metadata to be compatible with another version?
    m
    • 2
    • 1
  • a

    amadeu01

    03/25/2020, 6:37 PM
    what is the best of creating a generic object that has an argument in its constructor. For instance if I just need to create a new object that the class does not have arguments in its contructor I would be able to make
    T::class.java.newInstance() // Where T is a generic type
    But, if I want to make an new object that need to receive an argument. The usage of this would be in a recycler view where I have different view holders but each one has a constructor with only one argument. like
    inner class ShortTextViewHolder(
            private val viewBinding: ItemRowFormFieldTextBinding
        ) : RecyclerView.ViewHolder(viewBinding.root), FieldViewHolder {
    
            override fun configureWith(field: FormField) = viewBinding.run {
                with(field) {
                    textFieldName.text = label
                    textFieldDescription.text = description
                }
            }
        }
    So basically, I would like to simplify this
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view = ItemRowFormFieldTextBinding.inflate(parent.inflater)
            if (viewType == ITEM_TYPE_SHORT_TEXT) {
                return ShortTextViewHolder(view)
            }
            return LongTextViewHolder(view)
        }
    By calling a Factory like
    factory<LongTextViewHolder>(view)
    or
    factory(view, myPossibleTypes[viewType])
    where
    myPossibleTypes
    would be a list of the types I can instantiate
    a
    t
    • 3
    • 5
  • k

    kushalp

    03/25/2020, 8:53 PM
    If I had a data class that looks like
    data class Sample(val foo: Number)
    and the following example map that I may not know until runtime
    mapOf("foo" to 1, "bar" to 2, "baz" to 3)
    . How can I extract just the value that's relevant to the
    Sample
    data class and build it when I don't know if the field in question will be present?
    d
    c
    • 3
    • 4
  • m

    Miguel Vargas

    03/25/2020, 10:59 PM
    Looking in the flow builder I was confused by the type signature of the block param
    suspend FlowCollector<T>.() -> Unit
    In general what is the meaning of Type.()?
    l
    s
    • 3
    • 3
  • e

    Ellen Spertus

    03/26/2020, 12:13 AM
    How would I transform this list of pairs:
    val pairs = listOf(
        Pair("A", 1),
        Pair("A", 2),
        Pair("B", 3)
    )
    to this map:
    mapOf(
      "A" to listOf(1, 2),
      "B" to listOf(3)
    )
    i
    • 2
    • 2
  • b

    Burkhard

    03/26/2020, 9:40 AM
    Is there a function like
    Iterable.sum()
    that multiplies instead? I know I can use reduce to get the same effect, just looking for a cleaner way to code this.
    m
    s
    k
    • 4
    • 18
  • t

    thana

    03/26/2020, 12:55 PM
    why is a
    Sequence
    not
    Iterable
    ?
    m
    s
    +3
    • 6
    • 66
  • a

    Andreas Unterweger

    03/26/2020, 1:23 PM
    hello, i have a question related to inheritance and data classes in my specific case i receive the same object as json once with an enclosing data wrapper, and once in an object which has a list of that type:
    case 1: { data: {props.....} } -> StoredVehicleUserSingle
    case 2: { data: [ {props.....}, {props.....} ]  } -> StoreVehicleUsers with a list of StoredVehicleUsersList
    so far i have solved it like this:
    data class StoredVehicleUsers(
        @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, defaultImpl = StoredVehicleUserList::class)
        @JsonProperty("data") val vehicleUsers: List<StoredVehicleUser>
    )
    
    /**
     * we need to implementations for this for:
     * [StoredVehicleUsers] its [StoredVehicleUserList]
     * if its a single [StoredVehicleUser] we receive its [StoredVehicleUserSingle]
     */
    interface StoredVehicleUser {
        val vehicleId: String
        val userId: String
        val role: String?val roleTimestamp: Date?
        val resetRole: String?
        val resetRoleTimestamp: Date?
    }
    
    @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
    @JsonTypeName(value = "data")
    internal data class StoredVehicleUserSingle(
        override val vehicleId: String,
        override val userId: String,
        override val role: String? = null,
        override val roleTimestamp: Date? = null,
        override val resetRole: String? = null,
        override val resetRoleTimestamp: Date? = null
    ) : StoredVehicleUser
    
    internal data class StoredVehicleUserList(
        override val vehicleId: String,
        override val userId: String,
        override val role: String? = null,
        override val roleTimestamp: Date? = null,
        override val resetRole: String? = null,
        override val resetRoleTimestamp: Date? = null
    ) : StoredVehicleUser
    i think the solution is fine, the only thing that bugs me, is that i am repeating all properties in StoredVehicleUser, StoredVehicleUserSingle and StoredVehicleUserList, despite they are same. the implementations must be data classes to have euqal and hashcode. but if i use inheritance i actually must list all props in subclasses again and pass them to Super constructor. also a data class must have at least one constructor argument How can i do this better? (edited)
    t
    a
    m
    • 4
    • 16
  • h

    hooliooo

    03/26/2020, 3:14 PM
    Is there a library for doing combinatorial optimization?
    a
    • 2
    • 1
  • m

    mp

    03/26/2020, 4:35 PM
    Can someone clarify why reified types behave this way?
    s
    o
    a
    • 4
    • 10
  • t

    tony

    03/26/2020, 11:49 PM
    I'm looking at this issue on the gradle issue tracker (https://github.com/gradle/gradle/issues/2510), and the tl;dr is there's an issue with using -target and -source, and you can tell javac to use
    --release 8
    directly. My question is, with a Kotlin-only project, is there a way to tell it that in a gradle build script? I looked in
    KotlinJvmOptions
    and all its super classes, and didn't see any likely suspects. I tried passing it to
    freeCompilerArgs
    , but that complains its an unknown value.
    d
    f
    i
    • 4
    • 10
Powered by Linen
Title
t

tony

03/26/2020, 11:49 PM
I'm looking at this issue on the gradle issue tracker (https://github.com/gradle/gradle/issues/2510), and the tl;dr is there's an issue with using -target and -source, and you can tell javac to use
--release 8
directly. My question is, with a Kotlin-only project, is there a way to tell it that in a gradle build script? I looked in
KotlinJvmOptions
and all its super classes, and didn't see any likely suspects. I tried passing it to
freeCompilerArgs
, but that complains its an unknown value.
d

danny

03/27/2020, 12:56 AM
For Kotlin, you’re looking for
kotlinOptions.jvmTarget
on the compile task
https://kotlinlang.org/docs/reference/using-gradle.html#attributes-specific-for-jvm
t

tony

03/27/2020, 4:50 AM
ok. I am setting that, but it's unclear how it gets implemented (release vs target/source)
does
kotlinOptions.jvmTarget
use
-target/-source
or
--release
when writing java bytecode?
f

Fleshgrinder

03/27/2020, 4:54 PM
These options have no meaning for kotlinc as it produces its own bytecode with its own internal mechanisms. Setting
jvmTarget
to
8
will produce bytecode that is compatible with any JVM release that can interpret it, that's it.
t

tony

03/27/2020, 5:17 PM
ok, thanks
i

ilya.gorbunov

03/27/2020, 5:56 PM
If you want to build kotlin code so that it can run on specific JDK version, you should also specify path to that JDK in
kotlinOptions.jdkHome
parameter in addition to
jvmTarget
. This will ensure that you don't accidentaly use any API from a newer JDK.
t

tony

03/27/2020, 5:58 PM
I'll give that a try, thanks! I'm running into an issue where I'm trying to build with JDK 14 but run some tests on lower JDKs (because only Gradle 6.3 supports 14, and I test against lower gradle versions for my gradle plugin)
my project is entirely kotlin, with some tests written in groovy (spock tests)
unfortunately tests still fail. Something else is going on. I've raised it with gradle
View count: 3