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

    mathew murphy

    07/30/2019, 2:50 PM
    Kotlin stdlib could use a URI class, because java.net.URI is horrible.
    i
    m
    d
    • 4
    • 12
  • m

    Marcelus Trojahn

    07/30/2019, 3:38 PM
    I cant figure out how to pass that viewClass variable as parameter to setRoute... No matter what I do it always complains its the wrong type.
    m
    r
    k
    • 4
    • 25
  • s

    standinga

    07/30/2019, 4:04 PM
    when (i) {
    in 0..10 -> //
    in 10..20 -> //
    }
    c
    a
    +2
    • 5
    • 10
  • g

    Gunslingor

    07/30/2019, 6:25 PM
    I'm building a product/company that will need a android app, an ios app, a spring+kotlin backend and an angular cli frontend. So far trying to do all these in a single IntelliJ window has proven tough, so I sort of decided to run them as separate projects even though they are related to the same overall product. I sort of wanted to have them all in a single git repo, but I'm thinking now about separating them their too.... but then I might use kotlin native/multiplatform for the ios/android stuff so suspect a single git is better for this... trying to lay this out. Should I do 4 repos or one? How would I or do I want to treat these as one intelliJ project?
    Drawing1.pdf
    r
    c
    +3
    • 6
    • 20
  • g

    Gunslingor

    07/30/2019, 6:49 PM
    One other Question: I'm looking for project management software... I am used to managing multi discipline multi million dollar project using Excel for action items and Word for project planning, or alternatively MS Project/Primavera real PM software. I've used youTrack, trello, jira and I really really hate all three... jire and trello seem to manage project by sticky notes in swimlanes and youTrack is complicated and verbose, but provides less relevant functionality than excel and word for me. Bottom line, I want to use this modern developer PM software, but one thing I absolutely have to have is a tabular view with real columns, filter/sort without having to learn proprietary query languages... basically I need a real spreadsheet + pretty views for all the other people not managing the project.... Do any offer this?
    c
    t
    +2
    • 5
    • 20
  • n

    Nezteb

    07/31/2019, 4:27 PM
    apparently it’s
    val csvLines = generateSequence { csv.readMap() }.toList()
    k
    h
    d
    • 4
    • 5
  • n

    Nezteb

    07/31/2019, 5:59 PM
    Is there an easy way to interop between Kotlin `data class`es and more traditional libs that require Bean/POJO annotations? If I’m using a lib that requires annotations on a POJO/bean as well as normal getters/setters, I’d like to use a
    data class
    but I don’t think I can apply annotations to those fields.
    m
    • 2
    • 2
  • n

    Nick Halase

    07/31/2019, 6:21 PM
    Does Kotlin have anything currently or in the works along the lines of GroovyShell?
    m
    j
    +2
    • 5
    • 6
  • i

    iammini5

    07/31/2019, 9:26 PM
    Is there a suggestion to deal with the java type erasure from kotlin, i tried to use inline function and encounter the similar issue mentioned at https://youtrack.jetbrains.net/issue/KT-24888#tab=Linked%20Issues.
    s
    • 2
    • 1
  • a

    adolev

    08/01/2019, 12:44 PM
    Hi all! Is the Kotlin command line compiler incremental too, or do I need to use the Gradle/Maven plugin for that?
    m
    k
    g
    • 4
    • 8
  • n

    Nezteb

    08/01/2019, 8:12 PM
    Is there a lib other than OpenCSV that people use with Kotlin to read/write CSV files?
    c
    f
    g
    • 4
    • 3
  • r

    reik.schatz

    08/02/2019, 8:07 AM
    whats a good way to make sure a numeric (long) doesn’t overflow? how about
    val number = Math.max(x, x + y)
    m
    j
    • 3
    • 3
  • a

    arekolek

    08/02/2019, 11:41 AM
    Am i wrong to expect this to compile?
    sealed class Item {
        data class Foo(val id: Int) : Item()
        object Bar : Item()
    }
    
    fun List<Item>.trim() = dropLastWhile { it is Item.Bar || it.id == IGNORED_ID }
    It works if I do
    it !is Item.Foo || it.id == IGNORED_ID
    though, which is understandable
    d
    m
    w
    • 4
    • 8
  • r

    ross_a

    08/02/2019, 1:00 PM
    Does anyone know why
    kotlin.Number
    is an abstract class, rather than an interface?
    t
    e
    k
    • 4
    • 9
  • b

    bbaldino

    08/02/2019, 3:35 PM
    is there a trick to implementing preincrement for an inline class wrapping an int? post-increment is working fine for me but preincrement isn't
    r
    • 2
    • 12
  • m

    Marcelus Trojahn

    08/03/2019, 12:27 AM
    Hey, I'm a Vaadin guy but the recent changes on it are making me re-think it... Also, if I lose Vaadin I'd be inclined to drop Spring too since I already dropped Spring-data. Any advises on a web framework to create UIs on the server-side like Vaadin that would be nice to work with Ktor?
    r
    n
    • 3
    • 8
  • i

    Iaroslav Postovalov

    08/03/2019, 9:08 AM
    hi! i have a var with an internal setter. how can i apple @PublishedApi annotation to setter to be able to call it from inlined functions?
    public lateinit var command: CommandScope
            internal set
    s
    i
    • 3
    • 6
  • v

    Viktor Qvarfordt

    08/03/2019, 12:20 PM
    How can I have a type that represents a Double that is within a given range? For example I’d like to have a type that holds a double that is guaranteed to be between 0 and 1. I had a look at
    inline class
    but it does not provide
    init
    so I have nowhere to place an
    assert
    . Any ideas?
    d
    s
    k
    • 4
    • 18
  • b

    bod

    08/03/2019, 3:10 PM
    Hello, World! A small API design question: I'm making a lib in Kotlin, and want to make it nice to use from Kotlin and Java. One method takes a date range as a parameter so I used a
    Pair<Date>
    for it. This way from Kotlin it's nice, you can do
    foobar(dateFrom to dateTo)
    . But from Java you're going to have to do
    foobar(new kotlin.Pair<>(dateFrom, dateTo))
    and now you need Kotlin in your dependencies for this to work - not cool. Ideally I'd like to have both
    to
    and not this Java issue... Ideas?
    t
    m
    +2
    • 5
    • 8
  • b

    Big Chungus

    08/03/2019, 4:34 PM
    Is there any way to get kotlin property's default value?
    d
    r
    +2
    • 5
    • 14
  • b

    barteks2x

    08/03/2019, 7:55 PM
    I can't figure it out, is there any way to use java.* class using fully qualified name when there is something with name "java" already in scope?
    k
    • 2
    • 9
  • g

    groostav

    08/03/2019, 11:52 PM
    if I have a
    List<List<T>>
    which can be conceptualized as a "list of columns", (where each inner
    List<T>
    is a column), whats the most elegant collection method to use to get a list of rows?
    m
    k
    d
    • 4
    • 4
  • w

    wuseal

    08/04/2019, 9:00 AM
    Hi,Everyone,Could we have multiplatform channel in slack🙂 Iike mpp very much, hope we could have a place to comunicate with each other😊
    m
    • 2
    • 2
  • r

    Robert Jaros

    08/04/2019, 10:41 AM
    is there a multi-platform way to check if a variable (of type
    Any
    ) is a function/lambda?
    v is Function<*>
    works on JVM, but doesn't work on JS platform
    g
    d
    • 3
    • 9
  • s

    Stefan

    08/04/2019, 10:59 AM
    Hi, is there anywhere particular where I can chat about github in android studio?
    s
    g
    • 3
    • 9
  • i

    Ifvwm

    08/04/2019, 11:29 AM
    how to map a binary tree in kotlin?
    d
    k
    g
    • 4
    • 12
  • i

    Ifvwm

    08/05/2019, 3:40 AM
    there’s a var aob = ByteArray(1025) for socket, how I can clean this aob?
    g
    k
    +2
    • 5
    • 16
  • s

    Sergio Pro

    08/05/2019, 7:46 AM
    Could anyone explain why this works
    val longs = List(100) { random.nextLong(6868L) }
    assertThat(longs.all { it < 6869L }).isTrue()
    But when I use property access syntax for
    isTrue
    it throws
    Cannot infer type parameter SELF in val <SELF : AbstractBooleanAssert<SELF!>!> AbstractBooleanAssert<SELF>.isTrue: SELF!
    val longs = List(100) { random.nextLong(6868L) }
    assertThat(longs.all { it < 6869L }).isTrue
    I'm using assertJ. Just wondering if this is kotlin or assertj issue.
    w
    • 2
    • 1
  • k

    Kirill Rozov

    08/05/2019, 8:06 AM
    Hi. It will be great to have all leads of Kotlin User Group Leads in single place. Kotlin user group leads join in #kug-leads channel.
    👍 2
    a
    • 2
    • 3
  • m

    Maksim Vlasov

    08/05/2019, 10:21 AM
    Hi! What is the recommended approach to create an object, mutate it a little bit and then make it immutable? I use the following steps right now. A parent object has children mutable fields. Firstly, I create a parent object. Secondly, I create a child object. Then I set the parent object to the child object field. Thirdly, I set child field to the parent object. Lastly, I persist parent object.
    g
    s
    +4
    • 7
    • 27
Powered by Linen
Title
m

Maksim Vlasov

08/05/2019, 10:21 AM
Hi! What is the recommended approach to create an object, mutate it a little bit and then make it immutable? I use the following steps right now. A parent object has children mutable fields. Firstly, I create a parent object. Secondly, I create a child object. Then I set the parent object to the child object field. Thirdly, I set child field to the parent object. Lastly, I persist parent object.
g

gildor

08/05/2019, 10:22 AM
.copy method for data classes?
m

Maksim Vlasov

08/05/2019, 10:26 AM
thanks for response, but if it is not a data class?
it's an Entity class
s

spand

08/05/2019, 10:29 AM
Use a builder
g

gildor

08/05/2019, 10:32 AM
What is Entity class? Anyway, in Kotlin I tend to use completely immutable object with some copy method (like copy for data class but manually created)
m

Maksim Vlasov

08/05/2019, 10:33 AM
@spand thanks for suggestion. Could you provide an example?
g

gildor

08/05/2019, 10:33 AM
Because usually it’s just easier than create special builder
m

Maksim Vlasov

08/05/2019, 10:33 AM
@gildor I mean Hibernate entity class
b

Big Chungus

08/05/2019, 10:36 AM
Why can't you use data class for hibernate entity?
Another thing you could do is have all your object's properties be provided via custom delegate. Then implement the delegate to check for let's say
isLocked
property uppon setter invocation which is false by default and throw an exception if it's true. finally have a lock() method in your entity to set it to true when you;re done mutating.
It's not ideal, but that'll at least give you runtime safety for object's mutations.
m

Maksim Vlasov

08/05/2019, 10:39 AM
I don't use data class for hibernate entity, because it generates wrong equals(), hashCode(), toString() by default. However, I could override it.
Anyway, it seems strage to use data class just for copy method(
b

Big Chungus

08/05/2019, 10:50 AM
Here's a delegate snippet:
abstract class LockableEntity(isLocked: Boolean = false) {
  private var isLocked = false
  fun lock() {
    isLocked = true
  }

  protected class LockableProperty<T>(initialValue: T) {
    private var value: T = initialValue
    operator fun getValue(thisRef: LockableEntity, prop: KProperty<*>): T {
      return value
    }

    operator fun setValue(thisRef: LockableEntity, prop: KProperty<*>, value: T) {
      if (!thisRef.isLocked) {
        this.value = value
      } else {
        throw IllegalStateException("${thisRef::class.simpleName} is locked! Further property modification is forbidden")
      }
    }
  }
}

class SomeHibernateEntity() : LockableEntity() {
  var x: String by LockableProperty("Initial")
}

fun main() {
  val tmp = SomeHibernateEntity()
  tmp.x = "modified"
  tmp.lock()
  
  tmp.x = "Shouldn't succeed"
}
m

Maksim Vlasov

08/05/2019, 10:59 AM
@Big Chungus thank you! You recommend to use the approach only for mutable properties, aren't you? Could an Entity has immutable properties as well with such approach?
g

gildor

08/05/2019, 10:59 AM
Override hashCode/equals looks more tedious than write specific copy method
b

Big Chungus

08/05/2019, 11:08 AM
@Maksim Vlasov sure, just don't use the delegate for those and go straight for a plain
val x:Any = ???
👍 1
Here's an extended snippet:
import kotlin.reflect.*

abstract class LockableEntity(private var isLocked: Boolean = false) {
  fun lock() {
    isLocked = true
  }

  protected class LockableProperty<T>(initialValue: T) {
    private var value: T = initialValue
    operator fun getValue(thisRef: LockableEntity, prop: KProperty<*>): T {
      return value
    }

    operator fun setValue(thisRef: LockableEntity, prop: KProperty<*>, value: T) {
      if (!thisRef.isLocked) {
        this.value = value
      } else {
        throw IllegalStateException("${thisRef::class.simpleName} is locked! Further property modification is forbidden")
      }
    }
  }
}

class SomeHibernateEntity(x: String, y: Int, val immutable: Int) : LockableEntity() {
  var x by LockableProperty<String>(x)
  var y: Int  by LockableProperty(y)
}

fun main() {
  val tmp = SomeHibernateEntity("1", 2, 3)
  tmp.x = "1 modified"
  tmp.lock()

  tmp.x = "Shouldn't succeed"
}
Or you can also do that via interface
interface ILockableEntity {
  fun isLocked(): Boolean
  fun lock()

  class LockableProperty<T>(initialValue: T) {
    private var value: T = initialValue
    operator fun getValue(thisRef: ILockableEntity, prop: KProperty<*>): T {
      return value
    }

    operator fun setValue(thisRef: ILockableEntity, prop: KProperty<*>, value: T) {
      if (!thisRef.isLocked()) {
        this.value = value
      } else {
        throw IllegalStateException("${thisRef::class.simpleName} is locked! Further property modification is forbidden")
      }
    }
  }
}

class SomeHibernateEntity(x: String, y: Int, val immutable: Int) : ILockableEntity {
  private var locked = false
  override fun isLocked() = locked

  override fun lock() {
    locked = true
  }

  var x by ILockableEntity.LockableProperty(x)
  var y: Int  by ILockableEntity.LockableProperty(y)
}

fun main() {
  val tmp = SomeHibernateEntity("1", 2, 3)
  tmp.x = "1 modified"
  tmp.lock()

  tmp.x = "Shouldn't succeed"
}
And also interface with property-based approach
interface ILockableEntity {
  val isLocked:Boolean
  fun lock()

  class LockableProperty<T>(initialValue: T) {
    private var value: T = initialValue
    operator fun getValue(thisRef: ILockableEntity, prop: KProperty<*>): T {
      return value
    }

    operator fun setValue(thisRef: ILockableEntity, prop: KProperty<*>, value: T) {
      if (!thisRef.isLocked) {
        this.value = value
      } else {
        throw IllegalStateException("${thisRef::class.simpleName} is locked! Further property modification is forbidden")
      }
    }
  }
}

class SomeHibernateEntity(x: String, y: Int, val immutable: Int) : ILockableEntity {
  override val isLocked: Boolean
    get() = locked
  
  private var locked = false

  override fun lock() {
    locked = true
  }

  var x by ILockableEntity.LockableProperty(x)
  var y: Int  by ILockableEntity.LockableProperty(y)
}

fun main() {
  val tmp = SomeHibernateEntity("1", 2, 3)
  tmp.x = "1 modified"
  tmp.lock()

  tmp.x = "Shouldn't succeed"
}
s

streetsofboston

08/05/2019, 12:19 PM
What about having an interface with only read-only properties (only `val`s) and having a data class implement them with `var`s. When you're done mutating the data class instance, pass it as its parent-interface to code that can only read it. (You can do
override var
on a
val
)
💯 1
k

karelpeeters

08/05/2019, 2:27 PM
That's what I usually do as well, and what
listOf
does.
g

gildor

08/05/2019, 2:54 PM
It’s usually require much more code than copy/with function, tho more flexible and abstract
d

Dico

08/05/2019, 5:14 PM
Abstract isn't necessarily a plus for entities especially, I might pick builder approach here. But I probably wouldn't use hibernate in the first place.
b

Big Chungus

08/05/2019, 6:31 PM
Yeah, I'd prefer an interface myself
m

Maksim Vlasov

08/06/2019, 11:23 AM
@gildor The problem with data class is the following: when a new copy is created, I have to update all child's to the new object(
g

gildor

08/07/2019, 1:58 AM
Would be nice to see real code from your example, how many fields, why is this problem to create child object in a same
copy
way.
View count: 7