https://kotlinlang.org logo
Docs
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
  • m

    Mahendran

    10/03/2019, 11:31 AM
    Perfect way to Kotlin annotations processing ??
    c
    m
    • 3
    • 2
  • g

    gazpowell

    10/03/2019, 12:37 PM
    Hello all. Fairly new to Kotlin, but loving it so far. One area that is causing some consternation is that of JPA/Hibernate and the correct way to do it in Kotlin. All the blogs and articles that I’ve read on the subject appear to contradict each other with regards to whether to use data classes or not; what to put in the constructor; should properties be val or var. Can anyone point me in the direction of a clear and unambiguous example of how JPA/Hibernate entities should be defined in Kotlin? I’m look for the best practice.
    m
    t
    • 3
    • 2
  • m

    Mark Buikema

    10/03/2019, 12:56 PM
    Hi, is there a nice kotlin collection function like
    filter()
    , except it returns a list of the filtered items and a list of the unfiltered items? I need both lists
    b
    s
    • 3
    • 3
  • d

    Dias

    10/03/2019, 1:38 PM
    Why did other languages not incorporate the same system of nullable type to handle nullability like kotlin? It seems so intuitive and obvious to be done in the first place Are there any downsides of this approach that are not immediately obvious?
    b
    s
    +4
    • 7
    • 35
  • d

    Dias

    10/03/2019, 1:39 PM
    I am aware of optionals in most functional langugages, but it's not exactly the same
    a
    • 2
    • 9
  • l

    Luis Munoz

    10/03/2019, 3:25 PM
    what is the most kotlin idiomatic way to the following, so the code stays clean
    Untitled
    l
    p
    m
    • 4
    • 14
  • t

    temp_man

    10/03/2019, 6:44 PM
    I need some help with parsing a ByteArray. I have a byte array that needs to be parsed to usable data. The instructions say to format it with "IEEE-754 32-bit floating point (little Endian)". It also says it has an offset of 0 and length of 4. I'm not sure where to start with this. I have tried a few options but the data is not close to what I expect.
    s
    • 2
    • 20
  • c

    Cyril Scetbon

    10/04/2019, 1:30 PM
    Hey, any documentation reference on how to read configuration parameters from files and reload the app on configuration changes ?
    b
    m
    a
    • 4
    • 7
  • s

    snackycracky

    10/04/2019, 2:10 PM
    hey people, I try to do a reproducible build with ktor. I mean whenever I want to build a jar file and I didn’t change anything in the source then the jar should be exactly the same. It works for my spring-boot services but not for the ktor services: https://dzone.com/articles/reproducible-builds-in-java could someone achieve this and how ?
    • 1
    • 1
  • e

    Eugen Martynov

    10/04/2019, 4:19 PM
    Is this file updated? https://github.com/JetBrains/kotlin/blob/master/ChangeLog.md
    b
    • 2
    • 1
  • e

    Eugen Martynov

    10/04/2019, 4:19 PM
    Is there alternative source with what is changed?
    a
    • 2
    • 4
  • g

    groostav

    10/04/2019, 9:30 PM
    does kotlin have a magic fromString function for use with reflection? I've got a
    value: string
    and a
    KPropoperty1<*, T>
    , and I'm certain that the
    value
    is a `toString()`'d version of
    T
    and that
    T
    is a common value type (eg
    String
    ,
    Double
    , or
    enum class
    ). Is there a handy way for me to convert from my
    value
    to an instance of the `KProperty`'s return type? I can write the switch but I sorta feel like somebody should've handled this for me. I've got both guava and apache commons on my classpath
    c
    k
    • 3
    • 8
  • t

    tipsy

    10/04/2019, 11:08 PM
    anyone know when dokka 0.10.0 is going to be released?
    l
    • 2
    • 2
  • s

    Slackbot

    10/05/2019, 12:50 AM
    This message was deleted.
    :stackoverflow: 1
    v
    k
    • 3
    • 4
  • d

    dewildte

    10/05/2019, 2:14 PM
    Is there any reason Kotlin does not have a native Stack Data Structure?
    s
    t
    m
    • 4
    • 5
  • m

    marcinmoskala

    10/05/2019, 4:19 PM
    A question about nomenclature. Is is fair to say that generic functions are made by type parameter before those functions. The objection is that methods in generic classes are also generic functions so they can also be made by type parameter before hosting class. Is it so? Would you call such methods generic functions or rather methods in generic classes?
    k
    w
    • 3
    • 3
  • h

    Hexa

    10/06/2019, 8:14 AM
    Anyone use klint or detekt before? Please share your experience/recommendation on which one is better
    g
    s
    • 3
    • 2
  • y

    yawkat

    10/06/2019, 10:08 AM
    Is this a known bug? https://javap.yawk.at/#DK2APB/procyon - the constructor call to
    LocalSubType
    is missing the capture parameter
    a
    • 2
    • 5
  • d

    doodla

    10/07/2019, 5:52 AM
    What’s the kotlin way to do singletons? I know about `object`s but they’re not easy to test, or inject dependencies into ( unless i’m misunderstanding something ).
    d
    y
    g
    • 4
    • 4
  • s

    spand

    10/07/2019, 6:29 AM
    Is it possible to have an
    operator val invoke
    property ? The error message seems to suggest its possible but I cant find a way
    Modifier 'operator' is not applicable to 'member property without backing field or delegate'
    class Foo {
        companion object {
            operator val invoke = {}
        }
    }
    s
    k
    r
    • 4
    • 8
  • s

    Sergio C.

    10/07/2019, 10:59 AM
    but should it throw an Exception?
    d
    • 2
    • 6
  • j

    jmfayard

    10/07/2019, 11:03 AM
    How would you write a Kotlin script that replace all occurrences of a string in a file, overwriting the file i.e. in-place like sed:
    $ sed -e 's/find/replace/' -e 's/find/replace/' filename
    m
    • 2
    • 1
  • c

    Colton Idle

    10/07/2019, 11:11 AM
    How does everyone feel about the answer from @yole here? I personally really like using !! when I want to assert that something is not null at that point. https://discuss.kotlinlang.org/t/requirenotnull-or/1562/2
    s
    m
    +4
    • 7
    • 19
  • p

    pavel

    10/07/2019, 5:47 PM
    I have a piece of code that looks like this:
    fun pairTest(foo: Boolean, bar: Boolean) =
            when (foo to bar) {
                (true to true) -> 1
                (true to false) -> 2
                (false to true) -> 3
                (false to false) -> 4
            }
    IntelliJ is saying that I need an else branch here. How come? And is there a better way to do this?
    s
    r
    a
    • 4
    • 6
  • k

    kevin.cianfarini

    10/07/2019, 6:17 PM
    is it possible to write a function to get an enum from a value? I know in Java you would write a static function, but enums in kotlin can't have companion objects. Looking to get the enum associated with
    token
    here.
    internal enum class BencoderTokens(private val token: Byte) {
        INTEGER('i'.toByte()),
        STRING(':'.toByte()),
        LIST('l'.toByte()),
        DICT('d'.toByte()),
        END('e'.toByte())
    }
    s
    • 2
    • 3
  • s

    Sylvain Patenaude

    10/07/2019, 7:46 PM
    This is my 1st "real" Kotlin project, i.e. source code will be managed through Azure DevOps with Git. When creating a new repository from DevOps, there's a 'Add a .gitignore' field in the dialog with several options. For previous projects, we used to select "VisualStudio" because it's the IDE we used for these projects. However, for a kotlin project, would you select the obvious "kotlin" option? Or the "Gradle" option since the code will be built with it? Or some other option? Thanks in advance!
    w
    m
    k
    • 4
    • 5
  • b

    brain

    10/07/2019, 8:45 PM
    Has anyone seen this memory leak happening? It's causing an out of memory closure on our Android App every ~2 days or so. https://youtrack.jetbrains.com/issue/KT-34125
    k
    s
    • 3
    • 9
  • p

    Paul Woitaschek

    10/08/2019, 7:08 AM
    How can I clear the kapt cache? I use room and it always generates a dao class that was from another branch. When I delete the generated class it generates it again and then fails the build beause it references classes that do not exist.
    w
    m
    • 3
    • 5
  • o

    Olekss

    10/08/2019, 2:08 PM
    today got interesting confusion Method accepting parameter as Any type, and by kotlin syntax definition client invoked this method not with round brackets but with curly brackets, and as type is Any, the syntax and compiler accepted it and method was invoked with closure type, which broke the runtime Is it possible somehow to restrict or avoid such behaviour on compile time level?
    s
    s
    +2
    • 5
    • 9
  • r

    Robert

    10/08/2019, 4:27 PM
    What is the easiest way to extend an
    Map
    ? I tried extending
    HashMap
    but it is final. When I extend
    Map
    I have to implement all types of body functions like
    containsKey
    ,
    containsValue
    ,
    get
    ,
    isEmpty
    and properties
    entries
    ,
    keys
    ,
    size
    and
    values
    a
    i
    +4
    • 7
    • 17
Powered by Linen
Title
r

Robert

10/08/2019, 4:27 PM
What is the easiest way to extend an
Map
? I tried extending
HashMap
but it is final. When I extend
Map
I have to implement all types of body functions like
containsKey
,
containsValue
,
get
,
isEmpty
and properties
entries
,
keys
,
size
and
values
a

Alowaniak

10/08/2019, 4:42 PM
Perhaps
delegate
by?
i

ilya.gorbunov

10/08/2019, 4:48 PM
Try `AbstractMap`/`AbstractMutableMap`. Then you need to implement only a set or mutable set of entries.
r

Robert

10/08/2019, 4:49 PM
@Alowaniak not sure how
@ilya.gorbunov Ty! I can work with that
s

Shawn

10/08/2019, 5:09 PM
@Robert https://kotlinlang.org/docs/reference/delegation.html
👌 1
r

Robert

10/08/2019, 5:24 PM
When using the
AbstractMap
, how do I set the initial values? As I can't use
mapOf
to bootstrap it..
r

Ruckus

10/08/2019, 5:33 PM
You would need to define the appropriate constructor, and then a helper function like
robertMapOf(vararg Pair<K, V>)
or
Map<K, V>.toRobertMap()
m

Matteo Mirk

10/09/2019, 7:44 AM
From a design perspective, it’s never a good idea to extend a collection --unless you have some particular data structure need. I suggest you use composition, initialize your type with a map, and implement just the methods you need. Maybe with good names, meaningful to your domain.
s

Stephan Schroeder

10/09/2019, 12:21 PM
I can’t believe nobody mentioned extension functions yet.
r

Robert

10/09/2019, 6:57 PM
@Matteo Mirk I don't understand. If I have a map of items consisting of key-value, it would be wasteful to composite a list and re-implement all the methods like
contains
etc. Instead I just extend the existing class with methods and add some new ones. I don't see how that is "wrong"
@Stephan Schroeder I guess that could work, but I want to implement a specific list in this case, not add a function to all lists. I think that is what you mean?
@Ruckus Do you know of any example? I'm stuck on the last part of the code, for example
.apply
. I don't have and
putAll
method or something, as it's a normal map
class RobertMap: AbstractMap<Int, String>() {
    override val entries: Set<Map.Entry<Int, String>>
        get() = throw UnsupportedOperationException()
}
public fun <Int, String> robertMapOf(vararg pairs: Pair<Int, String>): RobertMap = RobertMap(pairs.size).apply {}
mapOf
does this, which seems to create a LinkedHashMap by default?
if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap()
r

Ruckus

10/09/2019, 7:14 PM
Well, depending on how simple you want to go, you could do
class RobertMap(vararg entries: Pair<Int, String>) : AbstractMap<Int, String>() {
    override val entries: Set<Map.Entry<Int, String>> =
        Collections.unmodifiableSet(entries.mapTo(mutableSetOf()) { Entry(it.first, it.second) })

    private class Entry(override val key: Int, override val value: String) : Map.Entry<Int, String>
}
which would let you use
val map = RobertMap(1 to "one", 2 to "two", ...)
r

Robert

10/09/2019, 7:18 PM
Aweomse! It doesn't seem to recognize
Colletions
but maybe that's because I'm in a MP project. So I thought an unmodifiable Map would be cheaper than a mutable one. But from the code I guess this is not true; as it is change to mutableSet before it becomes the unmodifiable set?
r

Ruckus

10/09/2019, 8:03 PM
Yeah, sorry,
Collections.unmodifiableSet
is a Java stdlib function. I was optimizing for readability / LOC. You could save it more efficiently and use your own implementation of an abstract set to access it.
👍 1
m

Matteo Mirk

10/10/2019, 2:57 PM
@Robert Composition doesn’t mean reproducing the whole interface of an associated object. Inheriting from a collection, and in general from a class you have no control over, is a bad idea because you’re forced to conform to its interface and internal representation, which maybe you don’t want (although there are use cases for it). The important question you want to ask yourself is: why do you need to extend a Map, what are you trying to achieve? If you need to build an enhanced version of a Map data structure (which means ALL Map interface + your methods or customized behavior) then okay go and inherit from
AbstractMap
, but it’s seldom the case. If instead you need a domain object that can be backed by a map, then I strongly advise to use composition and create your domain-specific interface, which of course won’t replicate any of the Map’s interface. If you need more explanation I can provide some code example, just ask.
View count: 9