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

    iex

    11/30/2019, 12:14 PM
    Hi! Just curious, is (out of the box) currying being considered? Or has it been discarded forever?
    r
    • 2
    • 1
  • h

    Hullaballoonatic

    12/03/2019, 9:17 PM
    What are some examples of features that made it into the language because they were proposed by the community?
    r
    • 2
    • 3
  • j

    jimn

    12/05/2019, 12:26 PM
    when i paste this into intellij i see
    r
    k
    k
    • 4
    • 45
  • l

    Leon K

    12/06/2019, 4:51 PM
    Proposal: I know this is unrealistic, but i'd love to maybe just start a discussion about how something resembling this could maybe be implemented. Record-types, which behave like a combination of rusts structs and elm's records. A Record-type would be a inline typedefinition which is structurally typed, so two records would have the same type if they share the same field types and names (elm-style) because of this, they would be defined via type-aliases, and the only way to add methods to them would be extension-functions. The big advantage of this structural typing: they can be row-polymorphic: you could define a function that takes a record-type with, say a name and age of a person, because it only needs this information. in your main code, you are working with a lot more information about any person, say their address, family-status, etc. you could then give your simple function that big person-object, and it would only have access to the persons age and name. this would be hugely beneficial for things like testing, where it could remove a lot of mock-objects, and also have the great benefit of functions really only taking the data they need, thus making their function-signature more expressive and the function-implementation safer (it cannot depend on data and information it should not depend on) this concept, for those interested, is implemented in elm under the name "extensible records", and is generally known as "row-polymorphism" (as seen in purescript, for example). another differenciating factor that these record-types would have is that they don't specify mutability or immutability in their record-type. say we have a record for a person ( i'm just gonna use purescript's record-syntax here):
    typealias Person =
      { name :: String
      , age :: Int
      , mobileNumber :: String
      , landlineNumber :: String
      , gender :: Gender
      }
    then this would not contain any information about the mutability of any of the fields. this is where the rust-inspiration comes in: Record-mutability would be defined on a per-usage basis. if you create a person (simplified here):
    val person: Person = { name: "Tom", age: 12, gender: Gender.Male } //other fields left out
    then this object is deeply immutable. this could be enforced by saying that a record can only store other Record-types or "primitive" types (and maybe a basic set of collections which are guaranteed to be immutable here) if you wanted to have a mutable version of that person, you would do something like this:
    val person: mut#Person = mut#{ name: "Tom", age: 12, gender: Gender.Male } //other fields left out
    (this demo-syntax is ugly, i know) this would mean that all fields of that record (and all fields of potential records stored within it) are mutable, and thus provide a setter (callable via normal
    =
    functions) turning a mutable record into an immutable one would need to be an explicit operation, because mutable records would be stored like normal classes (by reference), while immutable records would be stored and passed by value, thus be cloned wherever they are passed to. this approach would have a lot of benefits as well: - usually, you, the caller, know, if you need something to be mutable. thats why there are loads of classes that have mutable and immutable variants (
    List
    /
    MutableList
    , etc). this would make it possible to let YOU decide about the mutability your object needs - functions could guarantee purity in regards to the record by not requiring your arguments to be mutable, thus not being able to mutate them - you wouldn't need to create builder-classes, because you could just create a mutable version of the record, build your stuff, and then store it as immutable in the end - as a result of guaranteed deep immutability, the compiler could do heavy optimizations which are currently not possible. - you could still have mutating methods on the records, by just defining the extension-functions only for mutable versions
    m
    r
    +2
    • 5
    • 37
  • e

    eduardog3000

    12/22/2019, 10:22 PM
    Ok, stupid idea that I already have a counter-argument for: Implicit null return, if a function's type is nullable, reaching the end of the function without a return should implicitly return null. Problems: • Unit is currently the only implicit method return, adding another might make it confusing. • Only works for functions with explicit returns, idk if Kotlin has another feature with the same restriction (Nothing maybe?). • What happens if a function returns
    Unit?
    • Is this even useful?
    Untitled
    q
    j
    +2
    • 5
    • 12
  • b

    Ben Woodworth

    12/23/2019, 9:36 AM
    Has there been any discussion about adding a
    componentN
    operator that takes parameters? For `List`s and `Array`s, the standard library has to define
    component1
    -
    5
    functions, but a component operator with a positional argument could be used if it existed:
    component.kt
    e
    e
    +2
    • 5
    • 8
  • s

    Slackbot

    12/24/2019, 9:01 AM
    This message was deleted.
    d
    m
    • 3
    • 2
  • m

    Marc Knaup

    12/25/2019, 1:50 PM
    It would be great if we could to access file name, line number and maybe column number and function signature in Kotlin source code. Like
    #file
    and
    #line
    in Swift /
    __FILE__
    and
    __LINE__
    in C languages (for the latter see: https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#ID390). Values should be resolved at compile-time, not at run-time like for exceptions. That would be great for improving diagnostic logging in Kotlin DSLs, so that the DSL user has a rough idea where an error that has been reported by the DSL library has originated from. Exceptions won’t help here since in many cases you cannot throw them at the moment that a function has been invoked. Validation may take place at the very end. Also, using stack traces to get that info adds a lot of overhead at runtime and isn’t available in multiplatform/common code.
    ➕ 3
    i
    r
    • 3
    • 44
  • e

    eduardog3000

    12/29/2019, 12:53 AM
    quick, simple proposal
    Untitled.kt
    ➖ 2
    :yes: 1
    🇳🇴 10
    🤔 5
    m
    l
    • 3
    • 8
  • p

    pablisco

    01/09/2020, 11:28 PM
    What’s the rationale behind not allowing sealed classes on multiple files? One use case would be for Android’s RecyclerView and its Viewholder. If there are a significant number of cases it may get a bit too long to keep them all on the same file but on the other hand sealed classes are ideal for this kind of type where the number of implementations is known at compile time.
    b
    a
    e
    • 4
    • 4
  • j

    jdemeulenaere

    01/15/2020, 11:48 AM
    @DslMarker
    annotation class MyDsl
    
    interface TopLevelBuilder : MethodsThatShouldBeAvailableAnywhere, TopLevelMethodsOnly
    
    interface MethodsThatShouldBeAvailableAnywhere {
      fun doSomethingAnywhere()
    }
    
    @MyDsl
    interface TopLevelMethodsOnly {
      fun doSomethingAtTopLevel()
    
      fun lowerLevel(builder: LowerLevelBuilder.() -> Unit)
    }
    
    @MyDsl
    interface LowerLevelBuilder {
      fun doSomethingAtLowerLevel()
    }
    
    fun startDsl(builder: TopLevelBuilder.() -> Unit) {
    
    }
    
    fun main() {
      startDsl {
        doSomethingAnywhere()    // compiles
        doSomethingAtTopLevel()  // compiles
    
        lowerLevel {
          doSomethingAtLowerLevel() // compiles
          doSomethingAnywhere()     // doesn't compile
    
          this@startDsl.doSomethingAnywhere()  // compiles but is not very nice
        }
      }
    }
    j
    • 2
    • 2
  • g

    gregorbg

    01/19/2020, 9:31 AM
    Proposal: Add a convenience method for "unpacking" lists the functional way, i.e. like linked lists with a head element and the remaining tail elements.
    fun <T> List<T>.headWithTail() = firstOrNull() to drop(1)
    Obviously the function still needs a better name, but I find myself using this concept rather often when recursively processing list entries or working with data that is presented as a "heading + contents" table.
    val (heading, contents) = parsedCsv.headWithTail()
    j
    e
    +2
    • 5
    • 12
  • e

    elect

    01/29/2020, 11:26 AM
    while (true) { }
    might be simplified to
    while { }
    🤔 1
    ➕ 1
    d
    j
    +3
    • 6
    • 12
  • m

    Marc Knaup

    02/07/2020, 8:45 AM
    There should be a way to specify that a function’s type parameter is contravariant. Example:
    inline fun <R> Any.toIntOrElse(elseBlock: () -> R): R where Int: R = …
    should allow
    Int
    ,
    Int?
    ,
    Any
    and
    Any?
    as
    R
    .
    s
    d
    • 3
    • 11
  • s

    stantronic

    02/07/2020, 11:02 AM
    Someone has probably already proposed this, (if so please post the link) but I would find this syntax handy for when subjects
    when(someObject){
      .hasSomeProperty() -> doSomething
      .isBetterThan(someValue) -> doSomethingElse()
      else -> doAThirdThing()
    }
    Where
    hasSomeProperty()
    and
    .isBetterThan
    are either member or extensions functions on
    someObject
    ➕ 1
    k
    c
    +2
    • 5
    • 8
  • m

    Marc Knaup

    02/08/2020, 11:59 AM
    In property delegation right now the property name is only accessible when
    getValue()
    was called. It would be great if we could access the property name at the creation binding time of the delegate. Something like this:
    operator fun delegateProperty(thisRef: Any?, property: KProperty*) { … }
    Currently I have to pass the property name manually because it need to “register” the argument name and type way before the delegate’s
    getValue()
    is called.
    d
    • 2
    • 2
  • j

    janvladimirmostert

    02/08/2020, 3:29 PM
    Currently i'm getting an error when using vararg with inline classes, so my language proposal is to allow using vararg with inline classes
    inline class HotelCode(val value: String)
    suspend fun listHotels(vararg hotelCode: HotelCode) {
    ^^^ forbidden vararg type HotelCode
    d
    l
    • 3
    • 5
  • e

    elect

    02/12/2020, 5:10 PM
    local custom getter? (inside a function)
    d
    m
    • 3
    • 5
  • j

    jdemeulenaere

    02/13/2020, 10:08 AM
    Is there any plan to implement https://youtrack.jetbrains.com/issue/KT-4075 or any reason why this is difficult ? Can we help in any way ? I'm currently building a DSL and the API suffers quite a lot from not being able to overload setters 😕
    e
    q
    • 3
    • 12
  • l

    Leon K

    02/14/2020, 1:36 PM
    would it be possible (or even a good idea) to allow and maybe even encourage local name-shadowing like rust does? i.e. in rust, you can do
    let foo: String = "4".to_string();
    let foo: Option<i32> = foo.parse().ok(); // parse foo into the equivalent of Int?
    let foo: i32 = foo.unwrap_or(1234); // equivalent of foo ?: 1234
    i'd really love this for many reasons: - it keeps you from having to come up with either unreadable or needlessly complex names (i.e. here:
    fooString
    ,
    fooMaybeInt
    ,
    foo
    ) or - keeps you from alternatively having to combine everything into a giv method chain (which many times is preferable, in my example it would absolutely be preferable. but there are cases like more complicated in-between-steps where forcing everything into a single method-chain hurts readability badly (-> deep nesting, functions that take the value as an argument instead of as a receiver) - it would even be great to make this good-practice for nullable-let-stuff (i.e.:
    foo?.let { foo -> doSomething(foo) }
    is currently a warning, and using
    it
    is not a good option when this turns into more complex nested chains or
    doSomething
    is a longer call some arguments against it i've considered: # "just use var and mutate" - No. I do not want to use var where i dont need to dynamically mutate a variable. mutation should only be used when it actually represents mutation, not just to make code more readable in cases like this. also this does not allow for type-changes like in my example # "This hurts safety by allowing you to accidentally try to use a variable that has been shadowed " - Maybe, but it would not be a big problem. Most of the time, you'd use this to actually change the types like in my example. this would mean that you will get compiler errors immediately nearly every time. This is still by far the biggest argument against it, as i could see it making things less obvious in some rare edge-cases. but it does not hurt your actual safety as this is NOT mutation, but name-shadowing. # "This hurts readability, i dont like it" - this is subjective, but imo, No. First of all, rust get's away with it very well, and it does help rust a lot. (but rust does also work with wrapped types like Option<T> and Result even more than kotlin, so it IS more necessary there) - While shadowing variables can make for ambiguity on first sight, consider the ways this could help: - reduce the amount of nested methods and indents by encouraging putting things in seperate lines (one of the biggest reasons people like using method chains is that they don't need to think of names for their intermediate variables) - reduce the need for mutable variables. this is a big one. Using mutable vars where they are not strictly necessary does hurt your compile-time guarantees a lot more. - another thing about mutables: sometimes you NEED mutable vars if you work with stuff in loops (most of the time it's better to replace these with map, filter, etc, but there are cases where a simple loop is better). now, after your loop, your variable is still mutable. with this feature, you could then do
    var foo: Int = 0; for(...){/*change foo*/}; val foo = foo;
    and have it be immutable after the loop, again helping your compile-time guarantees. # "What would happen with nested scopes? wouldn't this be mutation?" - No. shadowing stays shadowing. if you shadow your variable inside a nested scope, this does not change the original variable. are there any points i've missed or any big arguments against it?
    s
    h
    c
    • 4
    • 8
  • d

    Derek Peirce

    02/15/2020, 9:13 PM
    Suppose I have the following code, where
    x
    is an `Int`:
    val y = x.takeIf { it > 5 } ?: 3
    The compiled bytecode becomes:
    Integer var2 = x;
    int it = ((Number)var2).intValue();
    int y = (it > 5 ? var2 : null) != null ? it > 5 ? var2 : null : 3;
    This has some undesirable boxing and unboxing, it would be ideal if the compiler could optimize this to the equivalent of:
    val y = if (x > 5) x else 3
    which compiles in Java to:
    int y = x > 5 ? x : 3;
    What makes this particularly desirable? Consider the protobuf pattern: https://developers.google.com/protocol-buffers/docs/javatutorial#the-protocol-buffer-api
    public boolean hasId();
    public int getId();
    To avoid boxing, primitives are stored with a default value, and a bitfield to indicate which primitives are truly set. Otherwise, we would ideally have a single method:
    inline fun getId(): Int? = if (hasId()) getPrimitiveId() else null
    It is inlined so that any boxing elimination could be carried out across method calls. If the compiler could eliminate unnecessary boxing, then this call:
    if (proto.hasId()) proto.getId() else calculateDefault()
    could be replaced with the more straightforward:
    proto.getId()?: calculateDefault()
    👍 4
    f
    • 2
    • 3
  • e

    elect

    02/16/2020, 11:29 AM
    lambdas default parameters?
    q
    • 2
    • 2
  • p

    Pasha Tsier

    02/18/2020, 6:43 AM
    Hi all! Has anyone yet considered adding compile time variables to Kotlin? This could be done either through an
    @comptime
    annotation, or even as a Comptime<A> trait. They would act as normal variables but would be evaluated at compile time instead of at runtime. This would allow for very powerful patterns - doing things like compile time bounds or units of measure checking. It could even allow us to make the nullibility checking and elvis operators part of the standard library written in Kotlin, instead of being part of the compiler itself
    m
    d
    d
    • 4
    • 15
  • w

    wcaokaze

    02/25/2020, 8:53 AM
    Is there any plan like
    suppress keyword
    for
    @Deprecated
    ? e.g.
    @Depreated("message", suppressKeyword = "FOO")
    fun foo() {
    }
    
    fun bar() {
       @Suppress("FOO")
       foo()
    }
    i
    • 2
    • 2
  • m

    Marc Knaup

    02/26/2020, 9:40 AM
    Interface delegation in interfaces would be nice 🙂 Using default implementations.
    interface Foo {
    	fun foo()
    }
    
    interface FooDecorator : Foo by decorated {
    	val decorated: Foo
    }
    👍 1
    j
    j
    • 3
    • 11
  • j

    jimn

    03/09/2020, 7:44 AM
    i propose that delegation could be expanded to do more with vtable dispatch using a simple z-axis analogy. this may be delegation by some other keyword or name. https://youtrack.jetbrains.com/issue/KT-37346
    u
    • 2
    • 3
  • m

    Marc Knaup

    03/11/2020, 2:02 PM
    I would like this to be possible 😄 It should call
    Foo.invoke()
    rather than treating it as a trailing lambda since none is expected.
    fun main() {
        makeFoo() { // Too many arguments for public fun makeFoo(): Foo defined in root package in file main.kt
            42
        }
    }
    
    fun makeFoo() = Foo()
    
    class Foo {
        operator fun invoke(arg: () -> Int) {
            println(arg())
        }
    }
    f
    d
    • 3
    • 23
  • e

    elect

    04/02/2020, 9:16 AM
    I wish I could call the primary constructor in the secondary constructor body. I can overcome this by a top or static function, but I'd like to have it compact in the constructor body
    d
    • 2
    • 3
  • p

    pablisco

    04/02/2020, 4:59 PM
    Not sure if this is a proposal but I haven’t managed to find anything about it. We are migrating code from Java to Kotlin and make heavy use of the JVM annotations. Often we may have the proper Kotlin way of doing things and then create JVM accessors to avoid massive refactors. For instance, we have an object that had an internal representation of the type and we have moved them to be a sealed class (which makes more sense). In Java we had two static factory methods that we used on each case. Now, from Java we have the respective constructosrs for each type. To make the transition easier we have kept the old Java Factory methods (in Kotlin) so that we don’t change thousands of files (there may be fewer) We want to avoid kotlin components calling these methods. Is there any way (no matter how hacky) to make a function that can be called from Java but not from Kotlin? (a bit like the reverse of inline functions)
    d
    r
    • 3
    • 3
  • l

    LastExceed

    04/04/2020, 1:16 PM
    allow re-declaration of local variable. shadowed variable goes out of scope
    i
    • 2
    • 1
Powered by Linen
Title
l

LastExceed

04/04/2020, 1:16 PM
allow re-declaration of local variable. shadowed variable goes out of scope
i

ilya.gorbunov

04/04/2020, 6:30 PM
Something similar is proposed and discussed here: https://discuss.kotlinlang.org/t/rust-style-variable-shadowing/16338/46
View count: 1