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

    iex

    05/03/2020, 12:49 PM
    And another question. Trying out to debug my question above in a scratch file, I got the same output for 2 different digest instances, with different data. What am I missing?
    val digest = MessageDigest.getInstance("SHA-256")
    digest.update("bar".toByteArray())
    val str = digest.digest().toString(UTF_8)
    
    val digest2 = MessageDigest.getInstance("SHA-256")
    digest2.update("sldkjfskfjs".toByteArray())
    val str2 = digest2.digest().toString(UTF_8)
    
    // str == str2 --> true!
    j
    a
    • 3
    • 17
  • r

    Ryan

    05/03/2020, 3:52 PM
    why would this error message come up? anyway to disable with intellij ce? Normally kotlin works fine but i'm trying to write aws lambda function with kotlin. Using sam/gradle kotlin dsl.
    k
    d
    • 3
    • 3
  • o

    Ofir Bar

    05/03/2020, 5:56 PM
    Hey guys, not sure where to put it. What are the best place to find remote contract jobs (3 - 12 month jobs) as Kotlin/Android dev?
    d
    • 2
    • 1
  • v

    Venkat

    05/03/2020, 11:59 PM
    I have a below list val list = listOf("o=one", "t=two", "t=two", "f=four", "o=one", "t=two", "s=seven", "o=one") I wanna split it into list of the list contains [["o=one", "t=two", "t=two", "f=four"],["o=one", "t=two", "s=seven"],["o=one"]] Actually I want to group list by "o=" delimiter and the list will always have at least one "o=" value. How could I achieve this in Kotlin without creating mutable temp variables because of my code should be in the functional style? I have tried with group() and groupBy{} methods but couldn't get the expected result.
    c
    d
    j
    • 4
    • 6
  • h

    Hadi Lashkari

    05/04/2020, 10:01 AM
    Kotlin introduces itself as supporting functional programming but it inherited the poor typing system of Java! For instance if you try to do
    Pair(a,b) as? Pair<String, Boolean>
    where
    a
    or
    b
    can be null, there is a Java warning that says
    Unchecked cast: Pair<String?, Boolean?> to Pair<String, Boolean>
    . By supporting more strong typing system which supports generics type checking, we can make sure we're developing less buggy programs. I want to know is it possible to do so? For instance, why we cannot hold type info in the KClass in the runtime to check these kind of stuff? Thank you.
    g
    s
    s
    • 4
    • 21
  • c

    Chilli

    05/04/2020, 10:09 PM
    Is there any list of accepted (or at least very possible) upcoming features in Kotlin 1.4?
    d
    • 2
    • 1
  • n

    natpryce

    05/04/2020, 11:58 PM
    Is there a way to refer to shadowed top-level declarations explicitly? E.g. to call a top-level function from a method of an object in the same package that shadows that top-level function?
    d
    • 2
    • 7
  • n

    nwillc

    05/05/2020, 12:27 AM
    Anyone know if kotlinx.serialization exposes a streaming serialization API? I see internally it uses one but looks like it's internal. Basically I'd like to go object -> steam w/o a String in the middle.
    ➕ 4
    s
    d
    • 3
    • 3
  • j

    Jukka Siivonen

    05/05/2020, 8:47 AM
    Seems like every time I update IDEA to new version I get less performance, simple change takes several minutes to compile and and minute more until tests starts running. It seems that new features are keeping added and performance decreases, anyone else struggling with this?
    s
    r
    +2
    • 5
    • 5
  • v

    VladimirR

    05/05/2020, 11:04 AM
    hi, is there a way to specify multiple targets for one annotation? instead of using two annotations @field:JsonProperty("some") @get:JsonProperty("some")
    d
    • 2
    • 8
  • c

    christophsturm

    05/05/2020, 4:35 PM
    is it possible that in some cases kotlin generates methods that are not marked as synthetic, and have no associated source file? I’m using pitest for my project and pitest needs source files for all non synthetic methods (which makes sense imo) this is how the class looks in “show kotlin bytecode”: https://gist.github.com/christophsturm/1f46f14dde1a61a14ce449b0632f883c
    g
    • 2
    • 5
  • a

    Alex Kuznetsov

    05/05/2020, 6:33 PM
    Hi there, What is the idiomatic Kotlin way to expose a
    var
    as a read-only property. I need something like the following:
    class Something(...) {
    var counter_ = 0
    
    fun doSomething() { 
    (snip)
    counter_++
    (snip)
    }
    
    val counter: Int get() = counter
    Is there a better way?
    r
    • 2
    • 3
  • s

    Sami Eljabali

    05/05/2020, 7:52 PM
    Published my first article that tackles creating Design Systems to be used between Android, iOS, & Designers. Included are free projects for both platforms! https://uxplanet.org/the-one-system-every-best-in-class-digital-product-shares-e94f85a491d6
    💯 1
    🚨 4
    i
    • 2
    • 1
  • r

    robstoll

    05/05/2020, 8:23 PM
    stupid question, if I define
    targetCompatiblity
    in my build.gradle to be 8 but do not define
    kotlinOptions.jvmTarget
    to be 1.8, so it should be 1.6 per default, what is the compiler supposed to generate? I am asking because I came across
    java.util.function.Consumer
    in the resulting byte code and this one was introduced in 1.8
    i
    s
    • 3
    • 19
  • r

    Regan Russell

    05/06/2020, 3:26 AM
    probably wrong but something like:
    fun performRequest<T>(request: ApiMessage<T>)
    At a guess..??
    :thread-please: 1
    s
    j
    • 3
    • 4
  • m

    Mustafa

    05/06/2020, 10:31 AM
    Was there a Multiplatform channel?
    a
    m
    • 3
    • 4
  • g

    galex

    05/06/2020, 10:38 AM
    Hello, what’s the closest we can get to have a functionality like
    guard
    in Swift? The best we found for now is to implement a few functions of that sort:
    fun <A : Any, B : Any> guard(a: A?, b: B?, block: (A, B) -> Unit): Boolean {
        return if (a != null && b != null ) {
            block(a, b)
            true
        } else {
            false
        }
    }
    This allows us to run code on a few different types and check that the block ran to have an
    else
    part. What do you think? It there something better out there? I checked Contracts but you can’t imply a list doesn’t contain a
    null
    item, too bad.
    j
    f
    • 3
    • 8
  • l

    LastExceed

    05/06/2020, 12:54 PM
    I want to loop over the elements of a queue, and remove them in the process. is there a fancy way to achieve this with
    for (x in y)
    or do i have to remove them manually ?
    d
    d
    +4
    • 7
    • 19
  • i

    iex

    05/06/2020, 3:29 PM
    I've problems writing a test implementation for an interface:
    interface Preferences {
        // ...
        fun <T> putObject(key: PreferencesKey, model: T?)
        fun <T> getObject(key: PreferencesKey, clazz: Class<T>): T?
    }
    Force returning a specific object, for unit testing
    class PreferencesReturningObject<T>(val obj: T): Preferences {
        override fun <T> putObject(key: PreferencesKey, model: T?) {}
        override fun <T> getObject(key: PreferencesKey, clazz: Class<T>): T? = obj
    }
    How can I write this? (Without using Mockito or similar) Edit: It's "fixed" by writing
    obj as T
    (the class type parameter actually doesn't make sense, it can be just
    Any
    ) but wonder if there's a better way
    b
    • 2
    • 1
  • a

    Ananiya

    05/06/2020, 5:43 PM
    Does any one can help me solving out this problem
    fooing.kt
    d
    d
    • 3
    • 3
  • c

    cab

    05/06/2020, 8:10 PM
    hello. is there a damn place where a humble developer can rant about monads being better than coroutines? please, help me to a banter room.
    🎆 1
    🍿 2
    s
    i
    +2
    • 5
    • 5
  • o

    Ofir Bar

    05/07/2020, 2:32 PM
    Hey guys, Inside the
    Primitives.kt
    file, Inside the Int primitive, there are methods to convert the Int to other primitives but I don't see any implementation. I can't figure out how this conversion works. What am I missing?
    a
    z
    g
    • 4
    • 6
  • o

    Ofir Bar

    05/07/2020, 2:33 PM
    These are the methods
    a
    • 2
    • 1
  • i

    iex

    05/07/2020, 3:05 PM
    is there a shorthand to access an optional throwing an exception if it's not set?
    t
    r
    • 3
    • 17
  • t

    taer

    05/07/2020, 3:29 PM
    I'm liking the new timeAPI for Monotonic and TestTime. TimeMark is pretty awesome for most things where I mark time from a point. Only one slight issue. I have one place where I get a time given to me as a ZonedDateTime(instead of assuming now). Is there a way given a Clock and a ZonedDateTime to create a TimeMark?
    i
    • 2
    • 9
  • j

    Janelle Fullen

    05/07/2020, 5:31 PM
    Hi, is there a way to include the test classes of one subproject into another subproject so it can use them in its tests? I can't find a way to do this that works with my setup (I'm using the android plugin and multiplatform, and not the java plugin). (edited)
    🇳🇴 4
    t
    j
    w
    • 4
    • 5
  • y

    Yevhenii Nadtochii

    05/07/2020, 10:36 PM
    Hello! Does anybody know how to declare get() & set() for delegated properties correctly ? I'v tried like this and it haven't worked out.
    operator fun getValue(thisRef: Any, property: KProperty<*>): Any = properties[property.name]
            ?: throw IllegalStateException("Property ${property.name} hasn't been initialized!")
    
    operator fun setValue(thisRef: Any, property: KProperty<*>, value: Any) {
        properties[property.name] = value
        listeners[property.name]?.invoke(value.toString())
    }
    d
    • 2
    • 3
  • v

    Venkat

    05/07/2020, 11:06 PM
    I'm new to functional programming and I'm using Kotlin with arrow functional library. I would like to convert below function to pure. Each 
    func*()
     call returns a valid string and it's gets appended to the mutable string variable 
    returnString
    . As far as I know, FP functions should not use any mutable values. So how would I replace those string appending lines?
    private fun stringifyValue(): String {
                var returnString = String()
                returnString = returnString.plus("=")
                returnString = returnString.plus(func1())
                returnString = returnString.plus("+/")
                returnString = returnString.plus(func2())
                returnString = returnString.plus("@")
                returnString = returnString.plus(func3())
                returnString = returnString.plus("#")
                returnString = returnString.plus(func4())
                returnString = returnString.plus("%")
                returnString = returnString.plus(func5())
                returnString = returnString.plus("^")
                return returnString
    }
    d
    z
    • 3
    • 5
  • a

    Alex Wilson

    05/08/2020, 12:16 AM
    I'm looking for a way to make this more idiomatic. It's not the best solution, but it works at the moment. I'm looking to learn more about collection transformations and how I could possibly do this with built in Kotlin functions. Can anyone point me in the direction on maybe what functions (map, etc) I should be looking into? Thank you!
    fun main() {
    
        val list = """
            a,234,97654/
            b,23,ABC,
            b,44235,203
            a,234,97654/
            b,23,ABC
            b,44235,203
            49,234
            39,9291
        """.trimIndent().split("\n")
    
        var total = mutableListOf<String>()
    
        for ((index, value) in list.withIndex()){
    
            var sb = StringBuilder()
    
            var nextIndex = index
    
            if(value.startsWith("a") && value.endsWith("/")) {
                sb.append(value)
    
                while(list[nextIndex + 1].startsWith("b")) {
                    sb.append(list[nextIndex + 1])
                    nextIndex++
                }
    
                total.add(sb.toString())
            }
        }
    }
    j
    m
    • 3
    • 12
  • f

    frogger

    05/08/2020, 9:31 AM
    Hi kotliners, I’m going to model permission rules. Nothing difficult per-se but since the “source of truth” is a spreadheet with rows “object status” and columns “user role” and cells “grant/deny” I was wondering if I should build a representation close to this so it is easier to visually compare with that spreadsheet source of truth. Anything better suited in kotlin than having and array of arrays for this? It is all static and only a 5x8 table.
    m
    b
    j
    • 4
    • 6
Powered by Linen
Title
f

frogger

05/08/2020, 9:31 AM
Hi kotliners, I’m going to model permission rules. Nothing difficult per-se but since the “source of truth” is a spreadheet with rows “object status” and columns “user role” and cells “grant/deny” I was wondering if I should build a representation close to this so it is easier to visually compare with that spreadsheet source of truth. Anything better suited in kotlin than having and array of arrays for this? It is all static and only a 5x8 table.
m

Michael de Kaste

05/08/2020, 9:40 AM
depends on how readable you'd want it. What does permissionRules[1][2] say? (That's access to one cell) What are the different object statusses? What are the different User Roles?
b

Big Chungus

05/08/2020, 9:44 AM
Represent a row as object and store it as
List<RowClass>
. Or if you want header colomn
Map<String, RowClassForNonHeaderColumns>
This way you can use type safe representations of your columns. e.g.
String
,
Int
,
Enum
f

frogger

05/08/2020, 10:27 AM
(sorry for the delay. work..)
depends on how readable you’d want it.
What does permissionRules[1][2] say? (That’s access to one cell)
It would say granted true/false
Ok, I see some kind of array of array or array of list is the best to try. the type-safe builder look like more suitable for tree models.
j

Jakub Pi

05/08/2020, 2:35 PM
Use data classes so that you have typesafe immutable representations with significant names for the underlying data, and then design your interface based on your lookup needs. For such a small table, you can get away with a List and just do a linear search. If it gets any bigger, put it into a Map with your search criteria as the key. Do not model it as a table, create a domain model and override toString() to spit out a table representation
View count: 1