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

    rrva

    07/03/2020, 5:58 AM
    do data classes support deep equals (a is equal to b iff the entire object graph that starts at a and b are equal) ?
    s
    m
    • 3
    • 6
  • i

    Ifvwm

    07/03/2020, 9:41 AM
    how to do type constraints in kotlin?
    m
    • 2
    • 1
  • a

    andylamax

    07/03/2020, 10:32 AM
    While we are at generics, What is the difference between
    fun <T> Foo()
    and
    fun <T:Any> Foo()
    ? So far I have just been using IntelliSense suggestions. I wan't to understand more. Any deep explanation?
    d
    a
    m
    • 4
    • 6
  • a

    andylamax

    07/03/2020, 11:45 AM
    How do I make this polymorphically serializable?
    @Serializable
    sealed class Result<out T> {
        @Serializable
        class Success<out T>(val data: T) : Result<T>()
    
        @Serializable
        class Failure<out T>(val msg: String) : Result<T>()
    
        companion object {
            private fun <T> resultContext(serializer: KSerializer<T>) = SerializersModule {
                polymorphic<Result<T>> {
                    subclass(Success.serializer(serializer))
                    subclass(Failure.serializer(serializer))
                }
            }
    
            fun <T> stringify(serializer: KSerializer<T>, res: Result<T>): String {
                return Json(context = resultContext(serializer)).stringify(
                    Result.serializer(serializer),
                    res
                )
            }
    
            fun <T> parse(serializer: KSerializer<T>, json: String): Result<T> {
                return Json(context = resultContext(serializer)).parse(
                    Result.serializer(serializer),
                    json
                )
            }
        }
    }}
    So that If I have a class
    @Serializable
    data class Person(val name:String)
    I can call
    Result.stringify(Result.Serializer(Person.serializer()),Result.Success(Person("Andy))) // This says class Person is not registered for polymorphic serialization
    I have little knowledge in Polymorphic Serialization. Also, I need to be able to serialize a
    Result.Success<Person?>(null)
    . Currently I don't know how to do so. Help?
    k
    • 2
    • 5
  • n

    Nishoobansal

    07/03/2020, 3:56 PM
    can somebody explain me the difference between inheritance and implementation and how they affect the memory of system?
    m
    a
    m
    • 4
    • 4
  • l

    Lost Illusion

    07/03/2020, 8:40 PM
    is it possible to reference an object's member as a kproperty1? rn if i reference a object's member i get a KProperty0 but for my use case it'd be nice if I could use a KProperty1 so i can bound the receiver.
    a
    d
    • 3
    • 7
  • a

    Ahmed Mourad

    07/03/2020, 10:08 PM
    Exceptions vs Result types, value-based classes and NoCopy. https://www.reddit.com/r/Kotlin/comments/hjoyxx/nocopy_compiler_plugin_for_kotlin/ https://www.reddit.com/r/androiddev/comments/hj3yq8/nocopy_compiler_plugin_for_kotlin/ Some interesting discussions were conducted here :)
    t
    • 2
    • 2
  • v

    Victor Harlan Lacson

    07/04/2020, 1:59 AM
    Hello everyone, I just created a library parsing csv files into data class without old java way of bombarding your data class with annotations. https://github.com/blackmo18/kotlin-grass hope it could be of good use to you. cheers
    👍 2
    a
    • 2
    • 1
  • t

    Thorkild

    07/05/2020, 10:33 AM
    Has anybody dug into any details around what makes Kotlin use a lot of memory when compiling? I've got a project that consists of a mix of generated and handwritten code and I've had to bump the compiler to 6GB memory to see it complete.. and I am curious. The project is only about 48000 lines (with whitespace) and 160-170 classes (+ a few data classes here and there). The largest kotlin class is 2600 lines long (with whitespace). (targeting jvm -- server style application)
    👀 4
    🙀 1
    d
    l
    +4
    • 7
    • 27
  • d

    Dmitry Kandalov

    07/06/2020, 11:15 AM
    Is there a single-page description of all the kotlin jars published here https://mvnrepository.com/artifact/org.jetbrains.kotlin? In particular, answering the question why would someone add a dependency on one of the jars to their project.
    🇳🇴 1
    a
    • 2
    • 1
  • n

    nfrankel

    07/06/2020, 1:14 PM
    hello stupid question of the day about this code snippet:
    while (shorteneds.putIfAbsent(url, this) != null) {}
    of course, intellij complains that the block is empty any idea how to write a better version without the complaint? i’m probably missing something from stdlib...
    d
    j
    +3
    • 6
    • 10
  • n

    Nishoobansal

    07/06/2020, 4:57 PM
    Hi, Can someone guide me to learn Kotlin. I am currently doing 'Kotlin bootcamp for beginners' by google. Where should I head next to learn more?
    z
    • 2
    • 1
  • f

    Fleshgrinder

    07/06/2020, 5:09 PM
    Anyone knows any good books on learning Kotlin? I was asked by a colleague today and didn't have an answer since I generally don't use books to learn languages.
    z
    m
    • 3
    • 5
  • d

    Dariusz Kuc

    07/06/2020, 5:53 PM
    [generics] hello 👋 Is there a nice way to avoid the extra cast below?
    fun <T : AbstractStub<*>> getClient(stubFactory: (Channel) -> T): T {
        val client = stubFactory.invoke(configuredChannel)
        return if (deadlineMs != null) {
            // returns AbstractStub<S>
            client.withDeadlineAfter(deadlineMs, TimeUnit.MILLISECONDS) as T
        } else {
            client
        }
    }
    was playing around with inlining the
    T
    but cannot get it to work --- doing the chaining call from from the caller works as expected
    val client: HelloGrpc.HelloBlockingStub = getClient { HelloGrpc.newBlockingStub(it) }.withDeadlineAfter(1000, TimeUnit.MILLISECONDS)
    j
    a
    • 3
    • 9
  • i

    itnoles

    07/06/2020, 9:00 PM
    How much more milestone release to final?
    s
    • 2
    • 1
  • g

    groostav

    07/06/2020, 10:59 PM
    So, the
    LinkedHashMap
    is a nice type in that its got the time complexities of a hash map and it preserves insertion order... but its implementation really is pretty gnarly. Does anybody have numbers on how its implementation impacts performance? Is there a more performant (and/or simpler and/or compact) implementation of an insertion-order-preserving-Map if I'm willing to give up some of the more esoteric intricacies of
    LinkedHashMap
    (eg: degradation to a b-tree if
    hashCode == 0
    , dynamic-checking for
    Comparable
    implementations, etc)? Immutability (even via copy-on-write) is also fine. I have maps that have an upper-bound size of 200, and I'm looking to get to lookups on the order of millions per second.
    j
    e
    m
    • 4
    • 3
  • o

    Orhan Tozan

    07/07/2020, 10:43 AM
    Regarding the new 1.4 version: When would one use
    fun interface CreateTodoUseCase { fun run() }
    over
    interface CreateTodoUseCase { operator fun invoke() }
    ? I see the latter being used alot for writing UseCases (myself included. Should I switch to functional interfaces instead?
    m
    j
    +2
    • 5
    • 8
  • j

    Jakekudur

    07/07/2020, 1:47 PM
    I want to make localization fully from a server, is it possible to load strings.xml from the server and substitute existing local strings.xml
    m
    v
    a
    • 4
    • 12
  • w

    william

    07/07/2020, 2:44 PM
    can i accept
    >
    ,
    <=
    , etc as an argument to a function?
    🇳🇴 1
    m
    m
    m
    • 4
    • 5
  • s

    Sam Garfinkel

    07/07/2020, 3:11 PM
    Does Kotlin 1.4 have a target date for a stable release?
    🙂 1
    d
    • 2
    • 3
  • x

    xii

    07/07/2020, 4:24 PM
    are companion objects overridable using inheritance on data classes?
    a
    • 2
    • 11
  • d

    dave08

    07/08/2020, 10:19 AM
    If I have:
    interface Something {
       fun foo(bar: Int): List<Int>
    }
    
    class SomethingImpl : Something {
       //...
    }
    
    val ref = Something::foo
    and I want to invoke it, do I do this:
    val instance = SomethingImpl()
    ref.invoke(instance, 5)
    ?
    m
    s
    • 3
    • 18
  • r

    Rob Murdock

    07/08/2020, 2:04 PM
    Two things I’ve wanted in Kotlin over the last year of tinkering: 1. function types that retain names and allow default arguments 2. a function on data classes that passes all the components as parameters to another function (like, a ‘destructure to target’)
    d
    a
    e
    • 4
    • 6
  • a

    asad.awadia

    07/08/2020, 3:14 PM
    Intellij now automatically adds ‘val’ when missed creating data classes arguments 😮 Best feature - functions don’t need val in parameters but data classes do
    😮 2
    s
    • 2
    • 1
  • j

    Jim

    07/08/2020, 4:36 PM
    Nevermind! Posted in #multiplatform
    f
    • 2
    • 3
  • x

    xii

    07/08/2020, 5:53 PM
    is there any way to get current iteration using generateSequence?
    g
    • 2
    • 14
  • t

    thana

    07/09/2020, 9:18 AM
    Any idea, why this fails? https://pl.kotl.in/EW-w9FlLK it says the general contract of
    Comparable
    is violated but io cannot spot the violation
    d
    m
    s
    • 4
    • 31
  • g

    Gilles Barbier

    07/09/2020, 3:03 PM
    Hi all, it may be (or not) a dummy question: how to you calculate a unique hash from a data class, in such a way that you have the guarantee (statistically) that two objects are different as soon as their hash are different? (hash may be calculated and stored on different servers at different time)
    m
    b
    +2
    • 5
    • 8
  • b

    bbaldino

    07/09/2020, 5:59 PM
    Is it possible to call an extension function on class A, defined in class B, from outside of class B? i.e.:
    class B {
       fun Int.answer(): Int { return 42 }
    }
    and somewhere else be able to do something like:
    fun main() {
            val myB = B()
            val num: Int = 10
            num.apply {
                myB.answer()
            }
    }
    My quick test tells me no, but is it imposible/nonsensical or am I just invoking it wrong? I want to be able to implement a function on some type A using some state from an instance of type B.
    s
    t
    • 3
    • 6
  • b

    bbaldino

    07/09/2020, 11:25 PM
    I have a function which takes in a
    KClass<T>
    and returns a function which takes a
    String
    and returns an instance `T`:
    fun <T : Any> getterFor(valueType: KClass<T>): (String) -> T
    One issue with this is that, due to type erasure, it doesn't work for things like
    List<Int>
    . I know `typeOf`/`KType` can help with this, but is there a typesafe way I can refer to a
    KType
    argument's type in the return type position? I.e. before I have
    T
    which matches between the argument (
    KClass<T>
    ) and the return type T...is there a way to do that with KType?
    fun getterFor(type: KType): (String) -> ???
    z
    • 2
    • 4
Powered by Linen
Title
b

bbaldino

07/09/2020, 11:25 PM
I have a function which takes in a
KClass<T>
and returns a function which takes a
String
and returns an instance `T`:
fun <T : Any> getterFor(valueType: KClass<T>): (String) -> T
One issue with this is that, due to type erasure, it doesn't work for things like
List<Int>
. I know `typeOf`/`KType` can help with this, but is there a typesafe way I can refer to a
KType
argument's type in the return type position? I.e. before I have
T
which matches between the argument (
KClass<T>
) and the return type T...is there a way to do that with KType?
fun getterFor(type: KType): (String) -> ???
I can do
fun <T : Any> getterFor(type: KType): (String) -> T
and then cast to
T
, but wondering if there's a way to 'enforce' a relationship between the KType and the return value's type
z

Zach Klippenstein (he/him) [MOD]

07/09/2020, 11:42 PM
inline fun <reified T : Any> getterFor(): (String) -> T {
  @Suppress("UNCHECKED_CAST")
  return getterFor(typeOf<T>()) as (String) -> T
}

@PublishedApi internal fun getterFor(type: KType): (String) -> Any {
  …
}
b

bbaldino

07/09/2020, 11:43 PM
🤦 Awesome. Thanks @Zach Klippenstein (he/him) [MOD].
I was trying to think of ways to use an intermediary function and that didn't occur to me.
View count: 1