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

    karelpeeters

    07/17/2018, 10:32 PM
    Can we play around with the inline classes feature already? Looks like I need to enable it in gradle, but what's the exact "keyword"?
    🙏🏼 3
    e
    • 2
    • 19
  • a

    Allan Wang

    07/18/2018, 4:22 AM
    My question geared towards whether things like
    fun Context.color(@ColorInt color: Int) = ContextCompat.getColor(this, color)
    , came at a cost of a method count. I made a library similar to ktx back when I first started with Kotlin, and I had always thought that it would come at no cost to a developer because inlined functions were fully inlined. I guess if proguard strips away the unused methods that works too, but now I’m more conscientious about what I add since inline didn’t behave as I originally thought.
    b
    • 2
    • 3
  • a

    Aregev2

    07/18/2018, 8:19 PM
    fun Date.Companion.factoryExtension() {
        
    }
    b
    e
    • 3
    • 3
  • d

    diesieben07

    07/18/2018, 8:19 PM
    What would
    this
    point to in such a method?
    b
    k
    • 3
    • 18
  • k

    karelpeeters

    07/20/2018, 10:37 PM
    Dammit just came across another use case for this:
    class Matrix {
        ...
        operator fun get(r: Int, c: Int) = ...
        
        inner object Transpose {
            operator fun get(r: Int, c: Int) = this@Matrix.get(c, r)
        }
    }
    ➕ 1
    k
    • 2
    • 3
  • a

    Allan Wang

    07/20/2018, 10:44 PM
    How would the notation work if you are calling from outside the Matrix class? An equivalent could be
    class Matrix {
       val transpose by lazy { Transpose() }
       ...
       inner class Transpose {
          ...
       }
    }
    Transpose still doesn’t really behave like an object though, since it’s tied to another class.
    b
    k
    • 3
    • 2
  • p

    pp.amorim

    07/21/2018, 4:35 PM
    So it’s just a layer over it 😰
    b
    • 2
    • 1
  • p

    pp.amorim

    07/21/2018, 6:12 PM
    a friend say that I can use traits
    k
    • 2
    • 1
  • a

    Aregev2

    07/21/2018, 8:12 PM
    Why again inline classes cannot inherit from super classes, what is the conflict?
    a
    b
    +2
    • 5
    • 22
  • g

    gregd

    07/24/2018, 1:15 PM
    Guys, is there any chance that top-level properties’ initialization could be deferred, just like in case of local variables?? Apple’s Swift works this way, and I find it very convenient and consistent, compared to what we have in Kotlin (there’s
    lateinit
    , but it only works with `var`s and non-primitive types). What I mean is that ALL properties (val, var, objects, primitives) could be defined without the initial value. And in case of accessing non-initialized property we would get an error, e.g. “variable ‘x’ used before being initialized”
    ➕ 1
    ➖ 3
    k
    b
    +6
    • 9
    • 33
  • a

    arekolek

    07/26/2018, 6:53 AM
    at the moment this code is invalid:
    interface Foo {
        val bar: Int
        fun getBaz(): Int
    }
    
    class Spam: Foo {
        override fun getBar() = 0
        override val baz get() = 0
    }
    I think what Andrey Breslav means is that to allow Kotlin properties override Java getters, this code would also have to be allowed to compile. I guess that if you look at Kotlin as a standalone language and not just "better Java" it makes sense that this code should not compile (but maybe there is a good reason for it to compile, other than Java interop, that I don't see?)
    k
    • 2
    • 1
  • a

    arekolek

    07/26/2018, 7:56 AM
    On a different note, would it ever be possible to have code like this (two values for simplicity) compile:
    enum class Bit {
        ZERO, ONE
    }
    
    fun test(bit: Bit): Int {
        if (bit == Bit.ZERO) {
            return 0
        }
        return when (bit) {
            Bit.ONE -> 1
        }
    }
    meaning exhaustive
    when
    , where some branches have been exhausted before the
    when
    ? Would that be something useful?
    a
    k
    r
    • 4
    • 4
  • l

    littlelightcz

    07/28/2018, 10:18 AM
    I am experimenting with the new
    runCatching
    feature and I am thinking about this use case: You want to process a list of files and after that you want to do a report about which file names succeeded and which didn't + what was the failure cause for each of them (or maybe possibly group failed file names by the same error etc.). Since now the Failure class contains only the exception, you lose the information for which original value it failed. Would it be possible to extend the Failure class to contain the failed value as well or is there a better way how to solve this use case?
    g
    l
    • 3
    • 12
  • l

    LeoColman

    07/31/2018, 6:44 PM
    Java API is amazing, that's why I'm asking. I can't use it in Android, for example, because these APIs aren't there for all android versions
    t
    s
    • 3
    • 4
  • o

    olek

    08/06/2018, 7:45 AM
    Hi all, long time Kotlin user here. I was thinking of improving the syntax for one-liner method calls inside lambdas. Imagine this code:
    names.groupBy { it.length }
    , one could use
    names.groupBy(String::length)
    , but it's kinda cumbersome in many cases, especially when chained, and it's unclear what happens when the method has arity of 1.
    names.groupBy(::length)
    would be shorter, but
    ::length
    is evaluated in the current lexical scope. How about something like
    names.groupBy(.length)
    ? Scala has
    names.groupBy(_.length)
    , Ruby has `Symbol#to_proc`:
    names.group_by(&:length)
    . What do you guys think?
    👍 1
    v
    k
    a
    • 4
    • 19
  • b

    Bernardo Ferrari

    08/07/2018, 2:36 AM
    Hi, there! I was converting some Swift code into Kotlin, and it feels weird, but AFAIK there isn't any way to deal with utf-8 strings + ranges, specially when there are emojis (or other special utf-8 chars). Example:
    val str = "a😀cde"
        val start = str.indexOf(str.first()) + 2
        val end = str.indexOf(str.last()) - 2
        val range = IntRange(start, end)
        println(str.substring(range)) // "should output 😀c, but will output ?c"
    Swift makes use of a Range<String.Index>, instead of Range<Int> (IntRange). The String Index is calculated based on a particular string so that it knows if there are any emoji or extended grapheme clusters. Don't you think would be nice to see a StringRange kind of thing on Kotlin? Source: https://stackoverflow.com/a/35193481/4418073
    g
    d
    • 3
    • 20
  • l

    louiscad

    08/07/2018, 9:51 AM
    Hi, why not add an
    asUnit()
    method in the #stdlib so you can do things like
    override someMethodReturningJavaVoidOrUnit() = launch { ... }.asUnit()
    ?
    d
    i
    • 3
    • 5
  • s

    ske

    08/09/2018, 12:18 AM
    Idea: Add the ability for interface delegates to be able to delegate to class members, and not just constructor parameters (eg. you can create a private val for a class if you just want to delegate to it without having the constructor inject it)
    a
    c
    • 3
    • 8
  • a

    alex.hart

    08/15/2018, 6:48 PM
    @ske one current “workaround” to this is to use a private constructor
    class Foo private constructor(private val barImpl: Bar): Bar by barImpl {
        constructor() : this(BarImpl())
    }
    a
    • 2
    • 2
  • d

    domfox

    08/16/2018, 5:11 PM
    More a standard-library issue than a language issue, but I've recently found myself missing these:
    inline fun <T, K> Sequence<T>.groupByAndReduce(keySelector: (T) -> K, crossinline reducer: (T, T) -> T): Map<K, T> =
            groupByAndReduceTo(LinkedHashMap(), keySelector, reducer)
    
    inline fun <T, K, M : MutableMap<in K, T>> Sequence<T>.groupByAndReduceTo(destination: M, keySelector: (T) -> K, crossinline reducer: (T, T) -> T): M {
        for (element in this) {
            val k = keySelector(element)
            destination.compute(k) { _, v -> if (v == null) element else reducer(v, element) }
        }
        return destination
    }
    
    inline fun <T, A, K> Sequence<T>.groupByAndFold(keySelector: (T) -> K, seedValue: A, crossinline folder: (A, T) -> A): Map<K, A> =
            groupByAndFoldTo(LinkedHashMap(), keySelector, seedValue, folder)
    
    inline fun <T, A, K, M : MutableMap<in K, A>> Sequence<T>.groupByAndFoldTo(destination: M, keySelector: (T) -> K, seedValue: A, crossinline folder: (A, T) -> A): M {
        for (element in this) {
            val k = keySelector(element)
            destination.compute(k) { _, v -> folder(v ?: seedValue, element) }
        }
        return destination
    }
    o
    i
    • 3
    • 3
  • r

    Ruckus

    08/22/2018, 4:40 PM
    EDIT: _As @Ilmir Usmanov [JB] pointed out, this would already be covered by _https://youtrack.jetbrains.com/issue/KT-7770 Proposal: Allow lambda syntax for for interfaces that derive
    FunctionX
    . I have a use case where I need a "recursive" function type, so I can't use a typealias:
    typealias Interceptor<T, U> = (Store<T, U>, U, Interceptor<T, U>) -> Unit  // Cannot be done
    I can define a specific interface to replace that like so:
    interface Interceptor<T, U> : (Store<T, U>, U, Interceptor<T, U>) -> Unit
    but that interface cannot be used as a lambda:
    fun <T, U> test(interceptor: Interceptor<T, U>) { ... }
    
    // You have to do this
    test(object: Interceptor<String, Int> {
        override fun invoke(store: Store<String, Int>, value: Int, interceptor: Interceptor<String, Int> {
            ...
        }
    })
    
    // I would like to do this
    test<String, Int> { store, value, interceptor -> ... }
    i
    u
    • 3
    • 4
  • i

    igor.wojda

    08/22/2018, 10:33 PM
    Android Kotlin Guidelines
    states that "When a function signature does not fit on a single line, break each parameter declaration onto its own line." From my observation there are certain cases where new line is also recommended - like (data) classes with multiple parameters in the constructor. Important advantage here is the fact that placing each parameter in new line makes code merge easier and often automatic. Because of that I wonder if someone before proposed to remove need of using
    ,
    when method parameters are explicitly separated by new line?
    data class Test (
            val param1:String,
            val param2:String,
            val param3:String,
            val param4:String
    )
    Proposal
    data class Test (
            val param1:String
            val param2:String
            val param3:String
            val param4:String
    )
    👍 6
    👎 7
    r
    s
    • 3
    • 3
  • c

    chalup

    08/31/2018, 3:05 PM
    I have a question about inline classes. The original announcement states that:
    Inline classes are similar to type aliases, but they are not assignment-compatible with the underlying value type, so you cannot assign a String to a variable of type Name, and vice versa.
    I'm wondering about the
    Name
    to
    String
    conversion part, i.e. let's say we have:
    inline class Name(val value: String)
    val name = Name("Jerzy")
    
    // old API that still uses raw String
    fun greet(val name: String)
    
    // the way we'd call the method with Name
    greet(name.value)
    I'm curious what are the negative aspects of automatic unwrapping, i.e. allowing the
    greet(name)
    call? I can't think of anything being terribly broken by this change, and it would allow gradual migration from bunch of
    String
    params to wrapped classes.
    a
    k
    • 3
    • 12
  • l

    LeoColman

    09/05/2018, 12:46 PM
    Hey guys! Let's discuss a bit about Multiplatform DateTime API? https://github.com/Kotlin/KEEP/issues/147
    k
    g
    v
    • 4
    • 5
  • d

    diego-gomez-olvera

    09/05/2018, 2:26 PM
    https://www.reddit.com/r/Kotlin/comments/7hoytl/kotlin_team_ama_ask_us_anything/dqsttz2/?st=jlp8kw4g&amp;sh=00cff5a4
    ❔ 1
    ❓ 1
    k
    l
    • 3
    • 3
  • k

    krtko

    09/06/2018, 8:16 PM
    I was thinking about how obtuse it is to have weak references in Java, do you think Kotlin could simplify that by adding weak/strong references as apart of the declaration of a variable like
    weak var something: Something? = someRef //of type WeakReference<Something> 
    if (something == null) { /*True if something's reference is null*/ } 
    var inferredWeakSomething = something //of type WeakReference<Something>
    strong var strongSomething = something //of type Something?
    e
    d
    • 3
    • 4
  • j

    jkbbwr

    09/07/2018, 3:38 PM
    I love keeping (get it) track of all the suggestions and changes, I just hope that kotlin doesn't change for the sake of change. It'd be bad to lose its way and just keep adding things
    ➕ 7
    p
    b
    +4
    • 7
    • 51
  • j

    jkbbwr

    09/07/2018, 5:34 PM
    @benleggiero I have an issue with
    [1,2,3]
    being both List<Int> and Set<Int> and Array<Int> depending on context.
    k
    i
    +3
    • 6
    • 28
  • d

    Dico

    09/13/2018, 9:46 AM
    I've submitted the KEEP, the associated issue can be found here: https://github.com/Kotlin/KEEP/issues/155
    g
    • 2
    • 3
  • k

    karelpeeters

    09/16/2018, 12:35 PM
    How many components do you want?
    t
    d
    +3
    • 6
    • 44
Powered by Linen
Title
k

karelpeeters

09/16/2018, 12:35 PM
How many components do you want?
t

themishkun

09/16/2018, 12:47 PM
Let’s discuss in thread. 1) It could be an arbitrary chosen number, like number of FunctionN interfaces (22) seems fine for any needs I can imagine (Anyway, anyone making a data class with more than 22 fields is a mad person for me) 2) I want just the generic
Component1<A>
,
Component2<A, B> : Component1<A>
etc.
k

karelpeeters

09/16/2018, 12:49 PM
Hmm I recall there being some change about this a couple months ago for the function interfaces, can't remember what exactly though.
d

Dico

09/16/2018, 12:58 PM
So the thing you suggest is the following:
interface HasComponent1<out A> {
    fun component1(): A
}
interface HasComponent2<out A, out B> : HasComponent1<A> {
    fun component2(): B
}
... etc, And these would be implemented by data classes implicitly? I used the interface naming of
HasComponent
as you can see, but it doesn't really matter either way.
t

themishkun

09/16/2018, 1:04 PM
@Dico exactly.
d

Dico

09/16/2018, 1:05 PM
Actually, if there's inheritance between the interfaces, that might allow destructuring of data classes when declaring less variables than properties of the data class 🤔
k

karelpeeters

09/16/2018, 1:12 PM
The problem is that giving meaning to position of properties is already leaning a bit on the "too implicit" side, but it's not that bad because it always happens very locally. If you make interfaces out of this behaviour you risk it spreading.
I would have liked the
componentN
behaviour to be opt-in for data classes, like for
data class Point(x: Int, y: Int)
it makes sense but less so for
Person(adress: Adress, age: Int)
. But that's too late anyway.
t

themishkun

09/16/2018, 1:16 PM
@Dico Kotlin supports contravariance, so that is not a big deal
d

Dico

09/16/2018, 1:19 PM
@themishkun sorry I do not understand how contravariance is relevant. I'm just saying it might be better to declare all of the properties and drop the inheritance to avoid the ability to destructure an instance using less variables than it has properties. This is because the compiler might check if it's an instance of
HasComponent2
for example to check if it's allowed with 2 variables, when it can also be a
HasComponent3
or
HasComponent4
. It would be weird. Anyway, it's not important. Just something small to consider for how the interfaces are implemented.
t

themishkun

09/16/2018, 1:24 PM
@Dico I now Understand your concern. Thanks. It will also secure the performance removing the need of bridge-methods
k

karelpeeters

09/16/2018, 1:28 PM
@Dico That is already how it works right now though:
val (a, b) = list(1, 2, 3)
@themishkun What are those bridge methods?
t

themishkun

09/16/2018, 1:29 PM
@karelpeeters https://docs.oracle.com/javase/tutorial/java/generics/bridgeMethods.html
d

Dico

09/16/2018, 1:30 PM
Hmm, good point @karelpeeters It's allowed for data classes as well, as I just tested:
data class Data(val a: Int, val b: Int, val c: Int)

fun test(data: Data) {
    val (a, b) = data // no error
}
Well, I guess the inheritance only simplifies implementation then.
k

karelpeeters

09/16/2018, 1:31 PM
Yeah both
List
and `data class`es have
componentN
function, no difference as far as the compiler is concerned.
d

Dico

09/16/2018, 1:33 PM
I see. It seems that for
List
,
componentN
function is defined up to
component5
. Maybe a little low for an upper limit for the rest of
HasComponent
types.
k

karelpeeters

09/16/2018, 1:34 PM
@themishkun I know about them, but aren't those only for input parameters? As far as I know there's no issue with returning more specific types, which is the only relevant part for the
componentN
functions.
d

Dico

09/16/2018, 1:34 PM
ah,
componentN
functions are operators. I didn't know that.
k

karelpeeters

09/16/2018, 1:35 PM
To be honest you should really stop destructuring after 5 values anyway.
a

Andreas Sinz

09/16/2018, 1:48 PM
You can do it already, so the only thing that this KEEP would add is auto-implement those interfaces on data classes?
d

Dico

09/16/2018, 1:49 PM
And add the interfaces to the standard library.
I guess.
t

themishkun

09/16/2018, 2:40 PM
@Andreas Sinz yes, and implement some library functions to use that advantage
k

karelpeeters

09/16/2018, 2:41 PM
For example?
t

todd.ginsberg

09/16/2018, 4:11 PM
Also, arity for 1.3 will be changing to 255, so that will be fun. component237() just strikes me as confusing. I kind of like the "If you are using more than component5(), find a different way" mentality.
k

karelpeeters

09/16/2018, 4:13 PM
Yes! That's what I was referring to earlier: https://github.com/Kotlin/KEEP/blob/master/proposals/functional-types-with-big-arity-on-jvm.md, thanks for reminding me.
👍 1
d

Dico

09/16/2018, 4:20 PM
I agree that there should be a sensible limit.
t

themishkun

09/16/2018, 4:25 PM
@todd.ginsberg I totally agree that there should be a far more limited ammount of
ComponentN
-s, I just referred to FunctionN current limit as some point to start evaluating. How did you choose this number when implementing FunctionN?
t

todd.ginsberg

09/16/2018, 4:26 PM
I don't have an objective way to decide on a number, if that's what you're getting at.
k

karelpeeters

09/16/2018, 4:28 PM
@themishkun What kind of use cases do you have in mind? Earlier on you said stdlib should add some functions using it, which ones?
t

themishkun

09/16/2018, 4:37 PM
@karelpeeters I mentioned some of them earlier. For example, a neat little function
inline fun <A,B,C> Component2<A,B>.consumeBy(f: ((A,B) -> C)): C = 
f(this.component1(), this.component2())
the usage is like with the spread operator for arrays:
fun drawAt(x: Int, y: Int)
Point(1,2).consumeBy(::drawAt)
d

Dico

09/16/2018, 4:38 PM
So is that essentially destructuring for function parameters?
t

themishkun

09/16/2018, 4:39 PM
another one would be a pattern-matching, used like
when (user) {
     in User("johnDoe", any()) -> ...
     in User(any(), 13) -> ...
     else -> ....
}
You could think of that as Mockito matchers, if you never met pattern-matching before
it becomes more interesting when combined with sealed-classes
k

karelpeeters

09/16/2018, 4:41 PM
Hmm how does that work? You want
in
to check each of the components, if
contains
isn't defined? And what does
any()
return here? Why are there
User
objects here?
t

themishkun

09/16/2018, 4:45 PM
this is the abstract example, the more realistic one would be
in (::User).pattern("johnDoe", any())
or any other syntactic trick that will make a
Pattern
object and give it some matchers. I can create a gist for you
@karelpeeters here is the gist with working typesafe no-reflection pattern-matching with ComponentN interface example https://gist.github.com/Mishkun/9430a6740858876895c1eb0f870b7a59
k

karelpeeters

09/16/2018, 5:20 PM
That does look promising indeed, although it's missing being able to capture those
any()
matches in a variable.
d

Dico

09/16/2018, 6:33 PM
well, any() can return an object whose
equals
always returns true. However, that would violate equals contract, and it would have to be the LHS of the comparison. It should probably be a contextual keyword of some sort instead. As for creating a
Pattern
object, I guess that would be cached statically for when expressions? It might be better to just inline the comparisons. Finally, what about:
in User(name = "mikhail")
This wouldn't be possible with the
componentN
functions however, but it would make sense semantically.
t

themishkun

09/16/2018, 8:34 PM
@karelpeeters unfortunately, i think there is no chance to really destructure things and bind variable to them without some syntactic shugar =(
v

voddan

09/18/2018, 4:34 AM
@themishkun one of the cons of inhereting data classes from generic interfaces would be boxing of primitives. Currently componentN functions do not box, but in your implementation they will
@themishkun another argument against this proposal is an idealogical one: in Kotlin accesing components by names is preferable to accessing components by their positions. The reason is that positional access makes automatic refactoring much harder. Destructuring itself kinda goes against that principal, so I think they want to keep it limited and underpowered.
Make sure to mention both if those concerns in the KEEP
View count: 3