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

    spierce7

    11/15/2019, 12:50 AM
    Can anyone tell me why I can’t debug my kotlin jvm app in IntelliJ? The Profile icon to run it is disabled. I’ve been trying to profile it for several hours now. Running works fine, but profile is greyed out.
    a
    • 2
    • 7
  • l

    liminal

    11/15/2019, 3:13 AM
    what is the difference between
    interface Foo<T : Any>
    and
    interface Foo<T>
    ?
    p
    s
    • 3
    • 5
  • d

    df

    11/15/2019, 10:02 AM
    can someone tell me how to configure maven to compile java code before kotlin? I'm using lombok on my java classes and kotlin can't access the accessors / mutators
    m
    a
    • 3
    • 2
  • f

    Fudge

    11/15/2019, 6:53 PM
    I'm guessing a blog post for 1.3.60 will be out after the weekend
    s
    m
    • 3
    • 2
  • y

    yawkat

    11/16/2019, 10:22 AM
    Why does += for MutableList behave differently from = with +? It's a bit weird and also against with liskov substitution because for List += works exactly like = with +
    m
    k
    +2
    • 5
    • 17
  • n

    nuhkoca

    11/16/2019, 4:22 PM
    OFF-TOPIC Anyone has an experience with
    yml or yaml
    files? I have below block in my config.yml however it throws below error:
    mapping values are not allowed here in "<unicode string>", line 95, column 18: filters:
    workflows:
      version: 2
    
      build_and_test:
        jobs:
          - build_and_setup
              filters:
                branches:
                  only: master
    I use
    CircleCI
    and in the official documentation, it shows the same usage. https://circleci.com/docs/2.0/configuration-reference/#full-example
    ✅ 1
    w
    g
    t
    • 4
    • 8
  • d

    Derek Peirce

    11/16/2019, 9:38 PM
    I have a covariance/contravariance issue.
    class Appender<out T1>(private val value: T1) {
        fun <T2 : T3, T3> addTo(list: List<T2>): List<T3> = (list + value) as List<T3>
    }
    
    fun main() {
        val appender = Appender(2.0)
        val list = listOf(1)
        val combined = appender.addTo<Int, Number>(list)
        println(combined)
    }
    Suppose I have an
    Appender
    class that creates a list by appending values to another list. The above code works for this, but: - It's necessary to specify
    T3
    - There's no guarantee here that
    T3
    is a supertype of
    T1
    , just
    T2
    From what I've seen, I can specify `T3 : T1, but not my aim of
    T1 : T3
    . Additionally, I would like
    T3
    to be inferred automatically, similar to how
    listOf(1) + listOf(2.0)
    gives
    List<Any>
    by default, but can be specified as
    List<Number>
    without issue. In particular, I would like
    Appender<Nothing>
    to return
    List<T2>
    without having to specify
    addTo<T2, T2>
    . (Obviously,
    Appender<Nothing>
    wouldn't be useful, but my use-case has other side effects. The method is also used to implement an interface, so converting it to a static extension method as is done for
    List + List
    isn't an option.) Does anyone know how this problem could be solved, or at least simplified, in Kotlin?
    k
    m
    • 3
    • 3
  • m

    magisu

    11/17/2019, 7:00 PM
    Hey guys, I have a quick question on Kotlin/SpringBoot. So if I am using SpringBoot to consume APPLICATION_OCTET_STREAM_VALUE, what type of class should I use to read the data? In Java I suppose I should use InputStream and read by byte[].
    m
    • 2
    • 2
  • m

    mzgreen

    11/17/2019, 9:54 PM
    I stumbled upon this interesting code sample today: https://discuss.kotlinlang.org/t/compound-extension/10722/41 Can anyone explain why does it behave like that?
    s
    f
    • 3
    • 7
  • j

    Jakub Gwóźdź

    11/18/2019, 8:13 AM
    Good morning. I have this stupid problem with generics-vs-overloading-vs-varargs in JOOQ. While following code:
    public class GenericsJava {
      public static Condition testJooqGenerics(Table<?> table, List<Object> list) {
        Field<Object> myColumn = table.field("MY_COLUMN", Object.class);
        return <http://myColumn.in|myColumn.in>(list);
      }
    }
    works well in Java, the Kotlin version
    object GenericsKotlin {
        fun testJooqGenerics(table: Table<*>, list: List<Any?>?): Condition {
            val myColumn: Field<Any> = table.field("MY_COLUMN", Any::class.java)
            return myColumn.`in`(list)
        }
    }
    yelds Overload resolution ambiguity:
    @Support public abstract fun `in`(vararg p0: Any!): Condition! defined in org.jooq.Field
    @Support public abstract fun `in`(p0: (Mutable)Collection<*>!): Condition! defined in org.jooq.Field
    Is there any way to work around this API issue?
    h
    • 2
    • 4
  • h

    henrik

    11/18/2019, 9:13 AM
    It seems 1.3.60 is released, but I can't find the release notes anywhere..?
    👍 2
    🤔 2
    l
    b
    • 3
    • 4
  • g

    gtrefs

    11/18/2019, 1:11 PM
    Hi all, I am not able to attend the KotlinConf later this year and would like to give my place to someone else. I payed for "Regular Admission" and would expect a similar price + tax. If you want to go and don't have a ticket yet, feel free to contact me.
    s
    • 2
    • 2
  • s

    Shumilin Alexandr

    11/18/2019, 1:39 PM
    Hi all, i am starting learn Kotlin. tell me please, can i use java and kotlin in one project? call methods Kotlin code from java code? for exemple
    :yes: 10
    j
    • 2
    • 6
  • s

    Stephan Schroeder

    11/18/2019, 2:21 PM
    I have to configure Jackson to return parametric types and it breaks my brain. So given a parametric type that’t either a single instance or a list of that instance:
    sealed class Data<T: Any> {
        class Single<T: Any>@JsonCreator constructor(@JsonValue val single: T?): Data<T>()
        class ListOf<T: Any>@JsonCreator constructor(@JsonValue val list: List<T>): Data<T>()
    }
    how do I created a correct typeRef for these to methods:
    private fun <T: Any> readResponseWithSingleData(
        jsonMapper: ObjectMapper,
        json: String
    ): Response<T, Data.Single<T>> {
        val typeRef = object : TypeReference<Response<T, Data.Single<T>>>() {}
        return jsonMapper.readValue<Response<T, Data.Single<T>>>(json, typeRef)
    }
    
    private fun <T : Any> readResponseWithListOfData(
        jsonMapper: ObjectMapper,
        json: String
    ): Response<T, Data.ListOf<T>> {
        val typeRef = object : TypeReference<Response<T, Data.ListOf<T>>>() {}
        return jsonMapper.readValue<Response<T, Data.ListOf<T>>>(json, typeRef)
    }
    The current code will compile but because of type erasure the real type T will be discarded and a
    LinkedHashMap
    is always used instead (which causes a ClassCast at runtime.) I can’t make these methods inline and use reified types because I pass both methods as parameter. I’m fairly certains that the answer is to use Jackson.TypeFactory.constructParametricType (https://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/type/TypeFactory.html#constructParametricType-java.lang.Class-java.lang.Class...- ) It’s just that the generic parameters T is so deep enbedded (it’s a bit more complex that the example provided in the API with
    List<Set<T>>
    ). What would the answer be assuming that I’d pass a third argument
    clazz: Class<T>
    to both methods?
    Response
    looks like this:
    data class Response<T: Any, D: Data<T>> @JsonCreator constructor(
        @JsonProperty("data") val data: Map<String, D>?,
        @JsonProperty("errors") val errors: List<String>?
    )
    t
    j
    • 3
    • 11
  • f

    Fudge

    11/18/2019, 4:38 PM
    Here’s something https://github.com/JetBrains/kotlin/blob/1.3.60/ChangeLog.md
    • 1
    • 1
  • z

    Zac Sweers

    11/18/2019, 4:54 PM
    Is there something potentially wrong with 1.3.60? Seems strange that it’s been released since Friday but nothing on the master branch changelog, releases, or any comms/announcements
    r
    m
    +5
    • 8
    • 25
  • h

    Hullaballoonatic

    11/18/2019, 5:23 PM
    when extending a java class or implementing a java interface that has
    getFoo
    defined but no
    foo
    , you cannot add
    val foo: Foo = ...
    to your kotlin class because of an "accidental override." Is there a way to tell the compiler you intended to override
    getFoo
    ? or am I required to use the syntactically awful
    private val foo: Foo = ...
    override fun getFoo(): Foo = foo
    e
    • 2
    • 1
  • a

    adams2

    11/18/2019, 5:24 PM
    do
    .javaClass
    and
    ::class.java
    return different values
    t
    • 2
    • 1
  • u

    user

    11/18/2019, 7:53 PM
    message has been deleted
    :kotlin: 18
    👍🏼 3
    🎉 26
    m
    • 1
    • 1
  • u

    user

    11/18/2019, 8:08 PM
    Kotlin 1.3.60 Released We’re happy to present the new release today, Kotlin 1.3.60. In addition to the quality improvements, this version focuses on: Optimizing the comparison of inline classes. Tooling improvements for debugging, J2K converter, and Gradle scripts written in Kotlin. Support for … Continue reading →
    👏 15
    r
    • 1
    • 1
  • s

    standinga

    11/18/2019, 11:56 PM
    Hey! What is an equivalent of Swift's failable initializer in Kotlin? Thanks! I have a Player and I want to init it with an asset, in case of not successful initialization I'd like player to be null, or at least throw.
    z
    s
    +2
    • 5
    • 13
  • s

    Slackbot

    11/19/2019, 3:22 AM
    This message was deleted.
    d
    l
    • 3
    • 2
  • f

    Fudge

    11/19/2019, 10:02 AM
    How can I call the
    super
    method in an overriden extension method?
    open class Foo {
        open fun Int.bar() {
            println("Bar")
        }
    }
    
    class FooImpl : Foo() {
        override fun Int.bar() {
            super.bar() // Unresolved reference
        }
    }
    In this case, how can I call
    Foo#bar
    inside
    FooImpl#bar
    ?
    🤔 1
    w
    i
    a
    • 4
    • 5
  • h

    Hexa

    11/19/2019, 10:22 AM
    Anyone has experience using Vert.X and Ktor? Please share recommendation which framework is better?
    a
    • 2
    • 1
  • s

    Sergey Chelombitko

    11/19/2019, 11:12 AM
    Are classnames enclosed in backticks permitted in Kotlin? This example compiles fine with 1.3.60 but Android Studio complains that
    Class name may only contain letters and digits
    o
    i
    s
    • 4
    • 3
  • s

    steenooo

    11/19/2019, 11:56 AM
    I was wondering if kotlin is used in minecraft server (spigot/bungeecord) plugins. I saw there was a minecraft channel, but it’s archived.
    r
    • 2
    • 1
  • c

    Constantin Weisser

    11/19/2019, 12:34 PM
    Can an anonymous object ever be non-final on the jvm?
    d
    d
    +3
    • 6
    • 11
  • j

    Joan Colmenero

    11/19/2019, 3:35 PM
    Any idea how can I do a
    getOrElse
    on my
    ResultWrapper
    class?
    sealed class ResultWrapper<out T> {
        data class Success<out T : Any>(val value: T) : ResultWrapper<T>()
        data class Failure<out T : Any>(val failure: Throwable) : ResultWrapper<T>()
    
        inline fun <B> fold(ifFailure: (Throwable) -> B, ifSuccess: (T) -> B): B =
            when (this) {
                is Failure -> ifFailure(failure)
                is Success -> ifSuccess(value)
            }
    
        companion object {
            fun <T : Any> just(t: T): ResultWrapper<T> = Success(t)
            fun <T : Any> raise(t: Throwable): ResultWrapper<Throwable> = Failure(t)
        }
    }
    I'm getting a
    Success(value=MyModel(....))
    And I need to do an
    Assert.assertEquals(expectedResult, result)
    where
    expectedResult
    is
    MyModel
    and
    Result
    is
    Success(value=MyModel(....))
    . Any idea?
    d
    w
    s
    • 4
    • 17
  • a

    Ashutosh Panda

    11/19/2019, 4:47 PM
    import kotlin.random.Random
    var number=3
    var rollDice:(Int)->Int={ number:Int->Random.nextInt(1 , 13)/number}
    fun roll(number,operation:(Int)->Int):Int
    {
        return rollDice(number)
    }
    println("${roll(number,rollDice)}")
    a
    • 2
    • 1
  • b

    bascan

    11/19/2019, 4:48 PM
    According to Idea this function doesn't contain a tail call. Any idea why?
    tailrec fun increment(i: Int): Int =
        if (i == 3) i
        else i + increment(i + 1)
    t
    a
    +3
    • 6
    • 11
Powered by Linen
Title
b

bascan

11/19/2019, 4:48 PM
According to Idea this function doesn't contain a tail call. Any idea why?
tailrec fun increment(i: Int): Int =
    if (i == 3) i
    else i + increment(i + 1)
t

todd.ginsberg

11/19/2019, 4:53 PM
Because the last call is the
+
not the
increment
function call
a

Ashutosh Panda

11/19/2019, 4:54 PM
what is a tail call
😂 1
e

eekboom

11/19/2019, 4:55 PM
lmgtfy:
https://www.baeldung.com/kotlin-tail-recursion
b

bascan

11/19/2019, 5:00 PM
@todd.ginsberg I factored the + out, but still got the same warning. What else could be wrong?
tailrec fun increment(i: Int): Int =
    if (i == 3) i
    else {
        val j = i + 1
        i + increment(j)
    }
s

sikri

11/19/2019, 5:01 PM
Tail recursion is when last action is evaluation of the same function. In your code for else branch last action is NOT
increment(j)
, but adding
i
to result of increment. Therefore, there is no tail recursion, as on stack should exist value of i and code should know about adding operation
☝️ 1
m

marstran

11/19/2019, 5:10 PM
If you want to make that function tail recursive, you have to add an accumulator as a parameter. That will allow you to make the recursive call last. Something like this:
fun increment(i: Int): Int {
  tailrec fun innerIncrement(i: Int, acc: Int): Int =
    if (i == 3) i + acc
    else innerIncrement(i + 1, acc + i)

  return innerIncrement(i, 0)
}
s

sikri

11/19/2019, 5:10 PM
tailrec fun increment(i: Int, acc: Int = 0): Int {
   return if (acc == 3) acc
  else {  
    val j = i + 1  
    increment(j, acc + j)
 }
}
m

marstran

11/19/2019, 5:10 PM
The wrapper function is just to keep the function signature the same.
s

sikri

11/19/2019, 5:10 PM
maybe that’s what you want
b

bascan

11/19/2019, 5:15 PM
@marstran @sikri Thanks for your snippets. I think I got it now, cheers.
👍 1
View count: 2