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

    aviran

    12/28/2019, 8:21 PM
    Hey, trying to figure out the basics here... reversing some code, how do I run middle() on the defined range? https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS4zLjMwIiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncyI6IiIsImpzQ29kZSI6IiIsIm5vbmVNYXJrZXJzIjp0cnVlLCJ0aGVtZSI6ImlkZWEiLCJjb2RlIjoiLyoqXG4gKiBZb3UgY2FuIGVkaXQsIHJ1biwgYW5kIHNoYXJlIHRoaXMgY29kZS4gXG4gKiBwbGF5LmtvdGxpbmxhbmcub3JnIFxuICovXG5cbnR5cGVhbGlhcyBFeHBvc3VyZVNlbGVjdG9yID0gSW50UmFuZ2UuKCkgLT4gSW50P1xuXG5mdW4gPFQgOiBDb21wYXJhYmxlPFQ+PiBtaWRkbGUoKTogRXhwb3N1cmVTZWxlY3RvciA9IHtcbiAgICB2YWwgaXRlciA9IGl0ZXJhdG9yKClcbiAgICB2YXIgbWluID0gaXRlci5uZXh0KClcbiAgICB2YXIgbWF4ID0gbWluXG4gICAgXG4gICAgd2hpbGUgKGl0ZXIuaGFzTmV4dCgpKSB7XG4gICAgICAgIHZhbCB0bXAgPSBpdGVyLm5leHQoKVxuICAgICAgICBpZiAodG1wIDwgbWluKSB7XG4gICAgICAgICAgICBtaW4gPSB0bXBcbiAgICAgICAgfVxuICAgICAgICBpZiggdG1wID4gbWF4KSB7XG4gICAgICAgICAgICBtYXggPSB0bXBcbiAgICAgICAgfVxuICAgIH1cbiAgICBcbiAgICAobWluICsgbWF4KSAvIDJcbn1cblxuZnVuIG1haW4oKSB7XG4gICAgXG4gICAgdmFsIGEgPSBJbnRSYW5nZSgwLDEwMClcbiAgICAvLyBob3cgZG8gSSBydW4gbWlkZGxlIG9uIGEgP1xuICAgIFxufSJ9
    h
    • 2
    • 3
  • s

    Slackbot

    12/28/2019, 10:03 PM
    This message was deleted.
    r
    k
    • 3
    • 7
  • a

    Animesh Sahu

    12/29/2019, 4:33 AM
    Is there more elegant way to attach a shutdown hook in kotlin, like lambda functions or so? Currently using this (not looks so beautiful :P)
    Runtime.getRuntime().addShutdownHook(object : Thread() {
    	override fun run() {
    		server.destroy()
    	}
    })
    i
    d
    • 3
    • 6
  • s

    steenooo

    12/29/2019, 1:49 PM
    Am I doing something wrong? I defined a var in the constructor. The var is used by the parent constructor. I can use the value. But when I try to update it, it says val can't be reassigned.. but it isn't a val
    t
    • 2
    • 2
  • t

    tateisu

    12/29/2019, 6:33 PM
    https://gist.github.com/tateisu/be6cdaee0a4e28186090fb3834899788 A quick speed comparison for
    apply {…}
    . Why three times slower ?
    q
    d
    • 3
    • 7
  • h

    Hullaballoonatic

    12/29/2019, 8:43 PM
    whooooaaaa I have never seen this before. Is this recent? Does this mean Kotlin might be getting union types in the future? That and default type parameters are some of my most desired features for the language. It would help so much with writing generic functions for differing number types, collections types, and more. The syntax of the hint is not valid syntax however
    d
    k
    +2
    • 5
    • 7
  • j

    James Hilliard

    12/30/2019, 2:50 AM
    when I build using java 13 it works fine, anyone know why setting
    kotlinOptions.jvmTarget = "1.8"
    in my gradle build doesn't work when using java 8?
    d
    • 2
    • 1
  • m

    Marc Knaup

    12/30/2019, 8:35 AM
    So, to denote that a function returns no value we use
    Unit
    . How should I denote that a parameter takes no value?
    Unit
    or
    Nothing?
    ? That’s relevant in a generic context like
    Visitor<Result, Data>
    where some visitors need no input and hence use
    Unit
    or
    Nothing?
    as
    Data
    .
    s
    • 2
    • 9
  • m

    Marc Knaup

    12/30/2019, 11:11 AM
    wow, nested typealiases actually work (inofficially)! I’m so gonna exploit that 😅 Why don’t we have them yet? 😕
    class Foo {
        @Suppress("TOPLEVEL_TYPEALIASES_ONLY")
        typealias Bar = String
    }
    
    fun main() {
        val hello: Foo.Bar = "hello"
    
        println(hello)
    }
    m
    • 2
    • 6
  • n

    Nir Yudovitz

    12/30/2019, 1:33 PM
    Hi, I have a map<string, any>, and I was wondering is there a way to access the values of the map As if they where variable names. Same way a with will work on an object.   Something like:
    map = mapOf("one" to 1, "two" to "2")
    magicWith(map) {
    one // 1
    two // "2"
    }
    (I don’t want to create a data class to reduce boilerplates)
    l
    m
    • 3
    • 19
  • a

    Animesh Sahu

    12/30/2019, 1:52 PM
    Is there way to add extensions to variables via delegation so that they may be reusable. Possible use case is to add a listener for the change in property, i know this can be done using external variable list containing lambdas and observable delegation but it is not reusable, as we need to create list for every variable we want to became observable, and it also doesn't reads/looks so good because you register observer lambda using member function of class not by the variable itself.
    m
    • 2
    • 17
  • a

    Alejandro Rios

    12/30/2019, 7:24 PM
    Hello hello, this might be a little off topic but, does anyone know where i can find info about the Hands on Labs of the Kotlinconf 2019? i thought those where videos but they are not
    👍 1
    👀 1
    r
    • 2
    • 1
  • d

    Daniel

    12/30/2019, 8:33 PM
    Might there a way to make a platform type non nullable in the interface? With:
    interface SharedPreferencesBuilder {
        fun build(): SharedPreferences
    }
    I have to denote the type in each implementation since the compiler warns me about the platform type
    q
    • 2
    • 2
  • g

    Gyuhyeon

    12/31/2019, 8:53 AM
    I'm confused with a somewhat basic concept -
    data class Foo(
        val bar: Long? = null
    )
    consider this simple class. Using mybatis, a
    select
    query from a database table is mapped into this class. I know that mybatis by default uses default noarg constructor, then uses setters to set the value. However, decompiling the above kotlin class reveals that bar is indeed
    private final Long
    . When default constructor is called, it seems to me that kotlin will use its synthetic method to automatically set
    bar
    as null. This would mean that bar cannot be set even with reflection magic. Does anyone have any idea how
    val
    fields could possibly be mapped correctly from mybatis?
    j
    m
    • 3
    • 10
  • j

    jimn

    12/31/2019, 9:18 AM
    var acc = 0
    val order = IntArray(a.size) {
        acc += a[it].size
        acc
    }
    is there a more succinct accumulator array creation than this?
    n
    • 2
    • 4
  • l

    LastExceed

    12/31/2019, 2:41 PM
    question about kotlin's language design: why are the primary constructor parameters specified next to the class name? wouldnt it be way more consistent with secondary constructors and other functions to have them next to
    init
    ?
    t
    • 2
    • 6
  • s

    steenooo

    12/31/2019, 7:00 PM
    Is it possible to provide a body to an elvis operator? If null, do this to acquire the value?
    n
    • 2
    • 2
  • s

    Shumilin Alexandr

    01/01/2020, 9:01 AM
    i want to use kali linux
    m
    d
    +2
    • 5
    • 6
  • l

    LastExceed

    01/01/2020, 11:28 AM
    data class Node(
    	val author: String,
    	val message: String,
    	val children: List<Node>,
    	val parent: Node = this
    )
    why is
    this
    not defined in this context ? context: Im making a chat client with tree structure instead of linear conversation. Every message is a comment on the message it replies to, except the root node which is a comment on itself (or should i make it nullable? i like to avoid nullability whenever possible)
    k
    m
    • 3
    • 40
  • l

    LastExceed

    01/01/2020, 2:37 PM
    fun foo(lastEntry: Entry) {
    	val myList = mutableListOf<Entry>()
    	var currentEntry = lastEntry
    	do {
    		myList.add(currentEntry)
    		currentEntry = currentEntry.parent
    	} while (currentEntry != null)
    	myList.reverse()
    }
    how can i simplify this pseudo code so I don't have to perform
    .reverse()
    at the end ?
    k
    d
    • 3
    • 31
  • p

    Paul N

    01/01/2020, 3:27 PM
    Is there a build in function to shift the contents of a list right or left ?
    e.g. list of 1,2,3 would go to 2,3,1 if I shifted right
    d
    • 2
    • 2
  • h

    Hullaballoonatic

    01/01/2020, 6:49 PM
    In intellij, is there an easier hotkey to hit to dismiss autocomplete suggestions than ESC? If not, do you have any recommendations?
    g
    • 2
    • 1
  • l

    LastExceed

    01/02/2020, 12:29 PM
    how do i properly send / receive a utf8 string over tcp using ktor ? code:
    fun main() {
    	runBlocking {
    		val tcpSocketBuilder = aSocket(ActorSelectorManager(<http://Dispatchers.IO|Dispatchers.IO>)).tcp()
    		val address = InetSocketAddress("127.0.0.1", 2323)
    
    		launch {
    			delay(100)
    			println("client: connecting to server")
    			val socket = tcpSocketBuilder.connect(address)
    			println("client: connected")
    			println("client: sending data")
    			val writer = socket.openWriteChannel()
    			writer.writeStringUtf8("hello world\n")
    			println("client: data sent")
    			println("client: done")
    		}
    
    		val serverSocket = tcpSocketBuilder.bind(address)
    		println("server: waiting for connection")
    		val client = serverSocket.accept()
    		println("server: client received")
    		val reader = client.openReadChannel()
    		println("server: receiving data")
    		val message = reader.readUTF8Line(999)
    		println("server: data received: $message")
    		println("server: done")
    	}
    }
    output:
    server: waiting for connection
    client: connecting to server
    server: client received
    client: connected
    client: sending data
    server: receiving data
    client: data sent
    client: done
    apparently the server gets stuck on receiving the string. why is that and how 2 fix ?
    d
    • 2
    • 2
  • v

    Vitali Plagov

    01/02/2020, 1:38 PM
    Hello. I have a code like:
    "one ".trim()
    "two ".trim()
    "three ".trim()
    I would like to improve it with use of scope functions like
    run
    ,
    with
    , etc. Can I do with them something like this:
    <scope_function> {
      "one ",
      "two ",
      "three ".
    }.trim()
    ?
    l
    s
    +2
    • 5
    • 18
  • j

    John Douglas

    01/02/2020, 4:44 PM
    Greetings. I have a very general question. We are designing a system that uses Flutter as the client/frontend. It's non-trivial (a POS system). We need to work offline. We'd prefer the business logic not be written in Dart as we'd like the share that logic server-side as well as prefer Kotlin. We can do it as a plugin to Flutter, but there may be some overhead. Are we correct in assuming that it precludes iOS? Is this a terribly bad idea for any other reason? Thanks in advance.
    d
    • 2
    • 4
  • a

    Amine

    01/02/2020, 5:46 PM
    Hello guys, happy new year! 🎉 Quick quesiton for kotlin-mpp, is there a way to apply the java plugin and the android one at the same time and avoid the following error:
    Error: The 'java' plugin has been applied, but it is not compatible with the Android plugins
    l
    • 2
    • 1
  • a

    Adam Hurwitz

    01/02/2020, 6:03 PM
    Any feedback on the way I've implemented parameterized unit tests in JUnit 5 with Kotlin would be much appreciated! 🙏 Embarrassingly when I started building the Unidirectional Data Flow (UDF) with LiveData pattern five months ago, I did not have testing experience. This made for a great opportunity to develop local unit testing fundamentals in Coinverse same code below. https://proandroiddev.com/android-unidirectional-data-flow-local-unit-testing-487a6e6f5c9
    👍🏻 3
    l
    • 2
    • 3
  • k

    Kris Wong

    01/02/2020, 6:48 PM
    I can't for the life of me get an executable JAR for my kotlin project. I have tried adding an artifact to my project and specifying Main-Class in MANIFEST.MF, but still I get "no main manifest attribute" when running
    java -jar
    l
    b
    j
    • 4
    • 30
  • s

    steenooo

    01/02/2020, 8:03 PM
    How should I handle a value that should be ignored in a
    when
    statement? in fx this situation
    enum Foo { FOO, BAR, FOOBAR }
    
    val foo = ...
    when(foo) {
      FOO -> sayFoo()
      BAR -> sayBar()
      FOOBAR -> do nothing
    }
    s
    l
    +3
    • 6
    • 12
  • k

    kyleg

    01/02/2020, 9:07 PM
    I’m trying to learn more about generics. I currently have
    interface Id
    
    inline class BarId(val value: Int): Id
    inline class BazId(val value: Int): Id
    
    sealed class Foo<T: Id> {
       abstract val id: T
       data class Bar(...): Foo<BarId>()
       data class Baz(...): Foo<BazId>()
    }
    
    fun <T: Foo<U>, U: Id> myFun(entity: T): U = TODO()
    Suppose I need to add a function to
    Foo
    that will take an Id param and spit back out a child class (the one that is affiliated with the Id implementation in question). So
    myBar.changeId
    should take
    BarId
    and spit out
    Bar
    . For example.
    sealed class Foo<T: Id> {
       ...
       abstract fun <T: Foo<U>, U: Id> changeId(id: U): T
    }
    I’m sitting here with
    data class Bar(...): Foo<BarId>() {
       override fun changeId(id: BarId): Bar = TODO()
    }
    not really knowing what to put for
    changeId
    . Obviously the implementation is going to be
    changeId(id: BarId): Bar = this(id=id)
    but I have to put some generics in the signature somewhere or else compiler/linter tells me this does not match the signature of Foo.changeId, which it is intended to override.
    s
    • 2
    • 4
Powered by Linen
Title
k

kyleg

01/02/2020, 9:07 PM
I’m trying to learn more about generics. I currently have
interface Id

inline class BarId(val value: Int): Id
inline class BazId(val value: Int): Id

sealed class Foo<T: Id> {
   abstract val id: T
   data class Bar(...): Foo<BarId>()
   data class Baz(...): Foo<BazId>()
}

fun <T: Foo<U>, U: Id> myFun(entity: T): U = TODO()
Suppose I need to add a function to
Foo
that will take an Id param and spit back out a child class (the one that is affiliated with the Id implementation in question). So
myBar.changeId
should take
BarId
and spit out
Bar
. For example.
sealed class Foo<T: Id> {
   ...
   abstract fun <T: Foo<U>, U: Id> changeId(id: U): T
}
I’m sitting here with
data class Bar(...): Foo<BarId>() {
   override fun changeId(id: BarId): Bar = TODO()
}
not really knowing what to put for
changeId
. Obviously the implementation is going to be
changeId(id: BarId): Bar = this(id=id)
but I have to put some generics in the signature somewhere or else compiler/linter tells me this does not match the signature of Foo.changeId, which it is intended to override.
s

StavFX

01/03/2020, 12:16 AM
Since Bar and Baz are data classes, you can just use the
copy
method to create a new instance with a different ID. Maybe you simplified your use-case before posting here, so not sure this will actually work for your real world purposes.
Also, this is pretty nasty, but it works
sealed class Foo<U : Id, S : Foo<U, S>> {
    abstract val id: U
    abstract fun changeId(id: U): S

    data class Bar(override val id: BarId) : Foo<BarId, Bar>() {
        override fun changeId(id: BarId): Bar = this.copy(id = id)
    }

    data class Baz(override val id: BazId) : Foo<BazId, Baz>() {
        override fun changeId(id: BazId): Baz = this.copy(id = id)
    }
}
👍 1
k

kyleg

01/03/2020, 5:39 AM
Thanks.
copy
is what I was using, but I omitted it so my question wouldn’t push potential answers in the direction I’d (possibly suboptimally) chosen. My issue was more around how to keep using the generics. I didn’t realize that I could reuse the class generic param in the function without re-declaring a generic in the function header itself. Problem solved, thanks!
s

StavFX

01/03/2020, 6:32 PM
Yeah.. that type of “recursive generics” (not sure if that’s a proper name, just what it looks like to me) is a bit odd.. but can help define a “self” type
View count: 8