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
language-proposals
  • a

    Alexis Manin

    10/07/2022, 8:13 AM
    I've just seen the new
    ..<
    operator. Will other mathematical range operators considered in the future ? Like open started (
    <..
    ?) Ranges, or fully open ranges (
    <..<
    ?) ? I think both are not very common, but maybe it would make sense to be exhaustive in this matter ? Maybe some mathematical libraries would have use for it ?
    s
    e
    • 3
    • 10
  • d

    dmitriy.novozhilov

    10/11/2022, 7:36 AM
    Because there is no syntax to specify type arguments for property access If
    T
    used in receiver then it's always possible to infer
    T
    from it (because all types in receiver should be inferred before call/access itself) But if
    T
    is used only in return type then there will be cases when compiler can not infer it, like
    val x = something // no information to infer T
    y
    d
    j
    • 4
    • 7
  • j

    janvladimirmostert

    10/11/2022, 8:31 PM
    context(A, B, C, D, E, F, G, H, I, J)
    someFunction() { ... }
    with (a) {
        with (b) {
            with (c) {
                with (d) {
                    with (e) {
                        ...
                        with(j) {
                            someFunction()
                        }
                    }
                }
            }
        }
    }
    I was thinking
    with (a & b & c & d & e & g & h & i & j)
    or
    contexts (a, b, c, d, e, g, h, i, j)
    that automatically generates that nested withs, but that's even messier obviously I've exaggerated the number of params, but if context receivers were to be used as a replacement for dependency injection (which seems like a brilliant use-case), I can easily see the number of params increasing as the number of services in a project increases. For now, the obvious workaround is just stashing all those fields in a single class and doing something like this:
    context(Alphabet)
    fun someFunction() {
        this@Alphabet.a.doSomethingWithA();
    }
    with(Alphabet(a = TODO(), b = TODO(), ..., z = TODO())) {
        someFunction()
    }
    Maybe this can become
    context class Alphabet(
        val a: A
        val b: B
        ...
        val z: Z
    )
    now if you
    context(Alphabet)
    , it puts all of those fields in context instead of the Alphabet class itself like a data class would have done. Also, if something has
    context(A)
    , I can just pass the whole
    Alphabet
    context instead of wrapping the call-site in
    with (this@Alphabet.a) { ... }
    since Alphabet already contains
    A
    b
    y
    e
    • 4
    • 3
  • k

    Kristian Nedrevold

    10/16/2022, 10:24 AM
    Why doesn't the Kotlin standard library provide something like Either? They already halfway provide it with Result, but as Result only takes a throwable it doesn't feel very useful. Why not just make Result be Result<out A, out B> ?
    r
    s
    j
    • 4
    • 5
  • m

    Marc Knaup

    10/16/2022, 11:03 AM
    I’d love to see
    @NoInfer
    being standardized. Any plans on that? Often you have to provide something like
    someDefinition<Type> {…}
    or
    resolve<Type> {…}
    - where you define something for a specific type. For example: • In dependency injection I want to force an explicit type to be provided. It’s too easy to accidentally infer a wrong type (esp. after refactoring something) and it’ll only result in an error sometime at runtime. • BSON / GraphQL type definitions. Here I want to be explicit for safety. Also, definition blocks can become quite long and if you have many across your project figuring out the type takes a while because it’s implicit. Last but not least type inferences seems to slow down compiler and IDE performance significantly.
    j
    • 2
    • 3
  • e

    elect

    10/21/2022, 9:38 AM
    I just read carefully what's new in 1.7.0 and after seeing "Allow implementation by delegation to an inlined value of an inline class", I wonder if it would be possible to do the same for (abstract) classes. In this way, unsigned numbers could extend the abstract class
    Number
    @JvmInline
    public value class UInt @PublishedApi internal constructor(@PublishedApi internal val data: Int) : Comparable<UInt>, Number by data
    and I'd be super happy because I don't have to create tons of additional and redundant constructors and methods specifically for every single unsigned (in glm)
    e
    • 2
    • 3
  • b

    Ben Woodworth

    10/22/2022, 2:46 PM
    How about allowing file-private receivers to be used in public functions? I could see this solving the need for a file-private accessibility modifier, and I can't thing of any immediate hard reasons this shouldn't work. I can see it being unintuitive, like accidentally using a file-private receiver and not knowing why it's missing from intellisense in other files, even if the receiver functions have a public modifier. Could be a suppressible warning but then it'd feel like a hack or awkward (I'm assuming
    context
    here is also an error, but just not reported as one yet since it's a prototype/experimental)
    s
    x
    • 3
    • 2
  • e

    elect

    10/25/2022, 6:58 AM
    I'm using extensively a trick to return multiple values with zero allocations, it's based on the idea of @louiscad, an example:
    class Vec2(val x: Float, val y: Float) {
        inline fun plus(s: Float, res: (resX: Float, resY: Float) -> Unit) {
            kotlin.contracts.contract { callsInPlace(res, kotlin.contracts.InvocationKind.EXACTLY_ONCE) }
            res(x + s, y + s)
        }
    }
    This code can then be called as
    val a = Vec2(0, 1)
    val b: Float; val c: Float
    a.plus(3) { x, y -> b = x; c = y }
    it's useful in hot loops (in 3d real time graphics) or, in Louis' example in Android, where you want to save any allocation you can Now, It'd be nice if Kotlin may automatically destructurize a lambda placed at the last place in a function signature without any allocations. That is something like:
    val a = Vec2(0, 1)
    val (b, c) = a.plus(3) { x, y }
    while underneath the compiler would automatically apply the code as shown in the first example Another nice advantage, which would come for "free", it's essentially using an argument parameter as a return one, overcoming the JVM limitation of not considering the return type as part of the function signature
    d
    • 2
    • 3
  • d

    dave08

    11/01/2022, 1:06 PM
    Maybe I'm missing something, but shouldn't there be an
    inner object
    declaration? Something similar to:
    class Foo {
       val num = 1
    
       inner class Bar {
          val one = "something $num"
       }
    
       val bar = Bar()
    
       init {
         // use it:
         println(bar.one)
       }
    }
    s
    e
    • 3
    • 18
  • e

    Emil Kantis

    11/09/2022, 2:58 PM
    Context receivers broken with functional interfaces? IntelliJ suggests replacing this
    object : MultipleElementDecoder<List<T>> {
            context(ByteArrayReader)
            override fun decode(numberOfElements: Int): List<T> {
                return (1..numberOfElements).map { readUntil('/').decodeNumericRange(block) }
            }
        }
    with this lambda:
    MultipleElementDecoder { numberOfElements -> (1..numberOfElements).map { readUntil('/').decodeNumericRange(block) } }
    But then it complains.. Not even sure what to start searching for in Youtrack.. 😞
    b
    • 2
    • 2
  • e

    elect

    11/11/2022, 11:07 AM
    I'd like Kotlin to include function return type in the signature.
    operator fun ByteBuffer.get(index: Int): Byte = ..
    operator fun ByteBuffer.get(index: Int): Int = ..
    Swift does that and it's great and the JVM underneath does include the function return type in the signature
    s
    • 2
    • 1
  • t

    themishkun

    11/14/2022, 10:36 AM
    Is there any youtrack issue / keep covering this topic? I find row-types one of the best features for any UI-client development.
    s
    • 2
    • 1
  • a

    ade

    11/16/2022, 9:03 AM
    Why is the following a warning, and not a compilation error?
    private fun String.hashCode() = 42
    e
    s
    • 3
    • 39
  • e

    Emil Kantis

    12/02/2022, 10:02 AM
    is there any way to say that all subtypes of a
    sealed interface
    should be data types?
    sealed data interface
    could perhaps be a nice addition? I would like to use
    copy
    with the subtypes.. 🙂 apologies for the low-effort proposal.. just want to get some discussion ✌️
    d
    s
    +2
    • 5
    • 6
  • h

    hfhbd

    12/04/2022, 11:40 AM
    Are there any plans to introduce a non-escaping anotation to disable escaping variables of a lambda?
    j
    k
    • 3
    • 5
  • m

    Michael Böiers

    12/07/2022, 8:57 AM
    We should provide the
    copy
    method in all classes that meet the necessary requirements - not just in data classes. A good use case for that are database entities. They have a lot of attributes, and if you model the entities as immutable (which I like to do), you really need to define them as data classes just to get the copy method. But since database tables can have cyclical references, you then need to remember to override hashcode, equals and toString to get back to default behavior. Otherwise you will run into stack overflow errors at runtime. That kind of sucks, when all I ever needed was the damn copy method!
    e
    a
    m
    • 4
    • 8
  • m

    Michael Böiers

    12/08/2022, 9:56 AM
    It would be really great to have something like takeUnless which allows you to include the element that fails the predicate:
    Iterable<T>.takeUntil(pred: (T) -> Boolean)
    or else, to make semantics more explicit, let’s add an optional parameter to takeUnless:
    list.takeUnless(includeBreakingElement = true) { … }
    or how about this:
    list.takeUntilIncluding { … }
    to that one we could also add an optional parameter indicating what should happen if no element matches. Callers could either want the entire list/stream returned, or an empty list (not possible for streams/sequences).
    d
    r
    j
    • 4
    • 12
  • e

    Emil Kantis

    12/09/2022, 2:45 PM
    Is there any reason why this works: (implementing a functional interface by delegation)
    object ColorEncoder : Encoder<Color> by { Encoder { appendable, t -> appendable.appendColor(t) }}()
    But inlining the lambda body to this doesnt:
    object ColorEncoder : Encoder<Color> by Encoder { appendable, t -> appendable.appendColor(t) }
    (I get that we can use a val instead, but would like to use objects to keep things consistent)
    k
    b
    • 3
    • 6
  • x

    xxfast

    12/13/2022, 11:15 PM
    Proposal to add
    zipWithNull
    (as seen on #advent-of-code)
    fun <T, R> Iterable<T>.zipWithNull(other: Iterable<R>): List<Pair<T?, R?>> = buildList {
      val first = this@zipWithNull.iterator()
      val second = other.iterator()
      while (first.hasNext() || second.hasNext()) {
        val left = if (first.hasNext()) first.next() else null
        val right = if (second.hasNext()) second.next() else null
        add(left to right)
      }
    }
    s
    • 2
    • 1
  • m

    Michael de Kaste

    12/15/2022, 8:19 AM
    AdventOfCode reminded me of functionality I have wanted in my enterprise software: Multiranges. Or at least the concept of having ranges with functionality for combining them. I want to be able to do Range.overlap(range: Range) and get a new range with just the part that overlaps. Or a multirange that can collect ranges and return the minimal multirange that contains all ranges. e.g.
    1..3 + 2..4 + 6..8 = Multirange(1..4, 6..8)
    j
    • 2
    • 2
  • v

    vngantk

    12/17/2022, 5:24 PM
    The two biggest missing pieces of Kotlin now are Union Types and Pattern Matching.
    i
    • 2
    • 1
  • c

    corneil

    12/18/2022, 11:41 AM
    Currying?
    i
    • 2
    • 3
  • e

    Endre Deak

    12/19/2022, 7:00 PM
    is there a way to assume from a generic that it's a data class type therefore it has the
    copy
    method in place?
    j
    k
    • 3
    • 2
  • m

    mattinger

    01/11/2023, 5:47 PM
    Does anyone know if there’s any plans yet for kotlin to introduce a type of value class (i know that keyword exists, but it’s for a single value inline class) that’s kind of like a data class, but without the backward compatibliity issues? Ideally it would follow the same rules (must have at least 1 val/var in the constructor, etc…) but generate only toStrings, equals and hashCode. And more importantly NOT generate the
    copy
    and destructuring functions which can cause backward compatibility issues in libraries. I was pointed to the https://github.com/drewhamilton/Poko library by someone, but i’m reluctant to use compiler plugins if i don’t have to, due to the current lack of a stable api which leads these plugins to have to adapter to the ever evolving plugin api.
    s
    k
    • 3
    • 2
  • e

    elect

    01/26/2023, 10:29 AM
    is there already a ticket about negating infix calls at the function name rather than at the receiver? ie,
    NavInput._DpadLeft !_isTest readMode
    s
    d
    • 3
    • 4
  • d

    dave08

    02/01/2023, 11:52 AM
    Any reason why:
    fun interface Foo { ... }
    // this works:
    data class Baz(val foo: Foo)
    val baz = Baz({ ... })
    // whereas this doesn't...
    fun baz(foo: Foo = { ... })
    // it needs to be:
    fun baz(foo: Foo = Foo { })
    why doesn't the compiler infer Foo as the lambda type in a default value of a function declaration?
    s
    • 2
    • 4
  • e

    Endre Deak

    02/15/2023, 8:51 PM
    is there any effort to generate DSL for the data class
    copy
    method?
    data class Foo(val bar: String)
    
    val foo = Foo("bar")
    foo.copy(bar = "bar1") // current
    
    // could be this:
    foo.copy {
       bar = "bar1"
    }
    e
    r
    +4
    • 7
    • 20
  • s

    Slackbot

    02/22/2023, 12:37 PM
    This message was deleted.
    a
    • 2
    • 1
  • m

    Michael de Kaste

    03/03/2023, 12:37 PM
    the ability to typealias extension on sealed subtypes
    sealed interface Range<T : Comparable<T>>{
       interface BoundedLeft<T : Comparable<T>> : Range<T>
    }
    val range: Range.BoundedLeft<LocalDate>
    typealias DateRange = Range<LocalDate>
    although the above statement is how we like to use it, the bottom two lines can't work:
    val daterange: DateRange.BoundedLeft (Unresolved reference: BoundedLeft)
    typealias DateRange.BoundedLeft = Range.BoundedLeft<LocalDate> (Redeclaration: DateRange)
    i
    • 2
    • 1
  • s

    simon.vergauwen

    03/06/2023, 2:04 PM
    Is there a proposal for ignoring receiver or context receiver for lambdas when passing method references? Similar to how you can pass a non-suspend method reference to a
    suspend
    lambda?
    Untitled.cpp
    h
    j
    e
    • 4
    • 10
Powered by Linen
Title
s

simon.vergauwen

03/06/2023, 2:04 PM
Is there a proposal for ignoring receiver or context receiver for lambdas when passing method references? Similar to how you can pass a non-suspend method reference to a
suspend
lambda?
Untitled.cpp
h

hfhbd

03/06/2023, 4:51 PM
How should it work if you access the context in
example
?
j

Joffrey

03/06/2023, 5:07 PM
@hfhbd the context is not provided by the
block
lambda in
example()
, it is expected by the lambda. So
example()
is actually supposed to create it and pass it to the lambda, not the other way around.
I think the question is about allowing
example(::one)
instead of forcing
example { one() }
if
one
doesn't use the context.
h

hfhbd

03/06/2023, 5:10 PM
yeah, but what should happen if you want to execute
block
inside example without a context provided?
fun <A> example(block: context(Fragment, View) () -> A): A { block(); TODO() }
Checking if the context is actually used could only work inside the module. Otherwise, a new version of the lib actually using the context would break the public api.
j

Joffrey

03/06/2023, 5:12 PM
I don't understand your question. `example`'s definition guarantees that
block
will be given a context (if called). So
example
has to provide one when it calls
block()
. That is irrelevant to whether callers of
example
pass a lambda that actually uses it
Basically it is already allowed to pass a lambda that doesn't use the context:
example { one() }
This could be simplified to
example(::one)
but the compiler is a bit too strict about the function signature to realize that it's ok.
There is no need to infer anything or detect any usage, by the way. It's just a matter of deciding that a function type without a context is sort of a subtype of the same function type but with context. Just like we do when deciding that a function without
suspend
keyword is kind of a subtype of the same function type with a
suspend
keyword.
h

hfhbd

03/06/2023, 5:22 PM
Ah, sorry I was confused. You are absolutely right, the context is not part of the example function but of the parameter. https://pl.kotl.in/jIDDXFwHM
e

elizarov

03/07/2023, 8:07 AM
KT-57165 Consider context conversion for callable references
s

simon.vergauwen

03/07/2023, 8:10 AM
Great, thank you @elizarov 🙏
View count: 6