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

    Matthias R

    01/08/2020, 10:02 AM
    Hey guys, I want to build a RESTful API with Kotlin. What is the best Framework for that?
    n
    r
    +5
    • 8
    • 10
  • j

    Joffrey

    01/08/2020, 11:37 AM
    What’s the preferred style to fallback to a default value when accessing a map?
    map[key] ?: defaultValue
    or
    map.getOrDefault(key, defaultValue)
    ?
    d
    m
    t
    • 4
    • 4
  • j

    jimn

    01/08/2020, 12:21 PM
    val stepsize = piv.size() / Runtime.getRuntime().availableProcessors()
                    (0 until piv.size() ) .step(  stepsize).map {
                        it until minOf(piv.size(),it+stepsize)                       
                    }
    is there an easier way of getting chunked IntRange sequences ?
    e
    j
    • 3
    • 26
  • i

    iex

    01/08/2020, 1:36 PM
    Not sure if
    gson
    lib question is correct here. Anyway. My problem: I'm parsing diverse JSON objects which come wrapped in a generic JSON structure. I have a function where I've to "unwrap" the nested objects, i.e. extract them from the generic structure and parse the nested object with a generic type
    T
    .
    g
    h
    • 3
    • 3
  • b

    Ben Madore

    01/08/2020, 6:52 PM
    trying to wrap my head around Contracts.
    class Person(val email: String?)
    inline class Email(val value: String) 
    
    fun Person.email() {
      return this.email?.let {
        Email(email)
      } 
    }
    basically an extension method on a class that will null-check a value and return it wrapped in an inline class. how do i tell the compiler that if the function
    Person.email()
    returns non-null then the
    instance.email
    property is also not null. is that possible? am i fundamentally misunderstanding contracts?
    l
    r
    +2
    • 5
    • 12
  • a

    Andrew

    01/08/2020, 10:09 PM
    I have a library with a few dependencies, org.json for example. If I want to use this in other projects without specifying the dependencies there was well it looks like I need to create a "fat jar" that packages up everything. I did that via gradle using the line below but now it includes everything such as the kotlin stdlib which seems a bit unnecessary, is that required or a way to exclude it? I can see how it might be needed if you used this library in a pure java project or maybe its just best practice to have it all for version conflict issues, not sure what is best practice here. jar { from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }}
    d
    g
    • 3
    • 4
  • j

    Jiri Bruchanov

    01/09/2020, 9:22 AM
    Hi, is there a way how to hide (at least for autocomplete) a kt function in java ?
    d
    • 2
    • 3
  • a

    Adriano Celentano

    01/09/2020, 10:26 AM
    shouldnt it be bad practice to do validation inside the constructor of a data class, when u can just use the copy method to create another “valid” object ? My best idea to solve it so far is to wrap a data class inside a normal class, to avoid the copy method, but still have the benefit of data classes
    d
    • 2
    • 3
  • i

    Ive Vasiljevic

    01/09/2020, 12:22 PM
    Is it possible to use generic type on a high order function? Like this? I need the type of the "function" to be inferred.
    Untitled
    d
    • 2
    • 1
  • i

    iex

    01/09/2020, 12:48 PM
    help, any ideas how to implement this?
    Untitled.kt
    r
    m
    +2
    • 5
    • 21
  • u

    uli

    01/09/2020, 1:03 PM
    Hi All, how is overriding properties with a backing field handled? Does the overridden property reuse the backing field of it's parent class? Or does it shadow it?
    g
    b
    • 3
    • 3
  • s

    simon.vergauwen

    01/09/2020, 2:41 PM
    Hi all, We were trying to bump Kotlin to 1.3.61 but ran into an issue where we cannot test
    internal
    anymore from the
    test
    folder of the module. Is this not allowed anymore?
    j
    t
    +3
    • 6
    • 16
  • v

    Vinicius Araujo

    01/09/2020, 2:42 PM
    Hi! Started working with kotlin in prod but still not sure if i'm doing that right/performatc way. Suppose I have a User collection and a Pair<UserId,Tag> collection, Each User object has a String collection property where I have to associate the given Tags owned by this user. In other words, a typical OneToMany join. Would this be the best way? How could I use parallelism in the outer loop (since the operations wont mix up cause every tag has its own user)?
    val users = getUsers().apply {
            val tags = <get list of Pair<userid, tag>>
    
            forEach { user ->
                user.tags.addAll(tags.filter { it.first == user.id }.map { it.second })
            }
        }
    k
    s
    • 3
    • 7
  • o

    Ofir Bar

    01/09/2020, 3:22 PM
    Hey guys, just curious. What this arrow symbolizes? Where I can read about it? I couldn’t find it on Google I am running Kotlin 1.3.50 with Coroutines
    r
    s
    m
    • 4
    • 5
  • z

    zak.taccardi

    01/09/2020, 4:27 PM
    For
    typealias
    naming - which style do you prefer?
    () -> Int
    // 1
    typealias ProvideNumber = () -> Int
    // 2
    typealias NumberProvider = () -> Int
    Usage then becomes either
    provideNumber()
    or `numberProvider()`/`numberProvider.invoke()`
    1️⃣ 2
    2️⃣ 16
    d
    d
    • 3
    • 13
  • j

    Jakub

    01/09/2020, 5:19 PM
    I have
    val items: Set<Any>
    that contains different types including
    EventItem
    . I wanna find in my set the index of
    EventItem
    with the specific date like:
    val event = state.items
        .filterIsInstance(EventItem::class.java)
        .find { it.start == date.atStartOfDay() }
                    
    val index = state.items.indexOf(event)
    However, it gives me
    Type inference failed. The value of the type parameter T should be mentioned in input types (argument types, receiver type or expected type). Try to specify it explicitly.
    What’s missing?
    s
    s
    h
    • 4
    • 5
  • g

    gcx11

    01/09/2020, 9:19 PM
    Hello, it is possible to use kotlinx-io in the multiplaftorm project? I have included
    implementation "org.jetbrains.kotlinx:kotlinx-io-common:$kotlinx_io_version"
    inside the commonMain block but gradle keeps saying it couldn't find such library
    Could not find org.jetbrains.kotlinx:kotlinx-io-common:0.1.16.
         Searched in the following locations:
           - <https://jcenter.bintray.com/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.pom>
           - <https://jcenter.bintray.com/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.jar>
           - <https://dl.bintray.com/kotlin/ktor/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.pom>
           - <https://dl.bintray.com/kotlin/ktor/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.jar>
           - <https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.pom>
           - <https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.jarCould> not find org.jetbrains.kotlinx:kotlinx-io-common:0.1.16.
         Searched in the following locations:
           - <https://jcenter.bintray.com/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.pom>
           - <https://jcenter.bintray.com/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.jar>
           - <https://dl.bintray.com/kotlin/ktor/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.pom>
           - <https://dl.bintray.com/kotlin/ktor/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.jar>
           - <https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.pom>
           - <https://repo.maven.apache.org/maven2/org/jetbrains/kotlinx/kotlinx-io-common/0.1.16/kotlinx-io-common-0.1.16.jar>
    According to ktor docs, it should work https://ktor.io/kotlinx/io/setup.html
    d
    • 2
    • 1
  • u

    ursus

    01/10/2020, 3:25 AM
    Also, even worse, what about different kotlin versions also?
    a
    i
    • 3
    • 3
  • n

    nitrog42

    01/10/2020, 9:55 AM
    hello, does anyone know a way to display the difference between two list (of data class) ? either by debug in ide or to a string like apache diffbuilder difference = which item and which part of the item is different
    p
    • 2
    • 1
  • o

    Olekss

    01/10/2020, 10:31 AM
    Hi, is it possible to cast to two interfaces at the same time... without having "combining" interface Like cast some object to Comparable and CharArray at the same type, so function of shape fun <T> doStuff(param:T) where T : Comparable, T : CharArray can use the cast object?
    s
    m
    • 3
    • 10
  • e

    EarthCitizen

    01/10/2020, 10:32 AM
    Does anything really disasterous happen if you call
    runBlocking
    from a coroutine scope or does it just take over the thread while executing?
    d
    • 2
    • 3
  • s

    spand

    01/10/2020, 12:04 PM
    Is there an easy way to get a
    KFunction1<T,R>
    from a closure ?
    • 1
    • 1
  • s

    spand

    01/10/2020, 1:06 PM
    Is there a better way to use the immutable builder pattern than this ?
    fun LocalDate.set(year: Int?, month: Int?, day: Int?) : LocalDate {
        var tmp = this
        if (year != null){
            tmp = tmp.withYear(year)
        }
        if (month != null){
            tmp = tmp.withMonth(month)
        }
        if (day != null){
            tmp = tmp.withDayOfMonth(day)
        }
        return tmp
    }
    b
    k
    • 3
    • 7
  • i

    iex

    01/10/2020, 1:24 PM
    Is there an elegant way to map from and to string values of an enum, which has to be deserialized by gson?
    enum class MyEnum {
        @SerializedName("my_foo") FOO // "my_foo" -> FOO (for deserialization)
        ...
    }
    
    MyEnum.FOO.string // FOO -> "my_foo"
    • 1
    • 1
  • a

    Andreas Unterweger

    01/10/2020, 2:29 PM
    hello together, a question concerning kotlintest. is it possible to organize tests via suite files like in junit or testng?
    m
    • 2
    • 1
  • v

    voben

    01/10/2020, 2:51 PM
    When using the
    when
    expression to test some cases, why do I have to use the
    is
    keyword sometimes, and other times I don’t?
    m
    d
    +2
    • 5
    • 9
  • m

    Michał Kalinowski

    01/11/2020, 9:38 AM
    is there any nice audio lib for kotlin?
    s
    s
    • 3
    • 3
  • l

    LastExceed

    01/11/2020, 1:15 PM
    would it be accurate to say that
    if
    is a top-level function with the following signature?
    fun if(condition: Boolean, action: () -> Unit)
    d
    s
    k
    • 4
    • 5
  • l

    LastExceed

    01/11/2020, 2:03 PM
    I tried to write a generic extension function for lists that returns all subsets of a given size that would be :
    fun main() {
    	val elements = listOf('A', 'B', 'C', 'D', 'E', 'F')
    	val subsets = elements.getAllSubsets(3)
    	subsets.forEach {
    		println(it)
    	}
    }
    desired output:
    [A, B, C]
    [A, B, D]
    [A, B, E]
    [A, C, D]
    [A, C, E]
    [A, D, E]
    [B, C, D]
    [B, C, E]
    [B, D, E]
    [C, D, E]
    here's my implementation:
    fun <T> List<T>.getAllSubsets(size: Int): List<List<T>> {
    	fun <T> getAllSubsetsRecursive(
    		elements: List<T>,
    		currentSubset: MutableList<T>,
    		remaining: Int,
    		minimumIndex: Int,
    		results: MutableList<List<T>>
    	) {
    		for (i in minimumIndex until elements.size - remaining) {
    			val currentSubsetCopy = currentSubset.toMutableList()
    			currentSubsetCopy.add(elements[i])
    			if (remaining == 0) {
    				results.add(currentSubsetCopy.toList())
    				continue
    			}
    			getAllSubsetsRecursive(
    				elements,
    				currentSubsetCopy,
    				remaining - 1,
    				i + 1,
    				results
    			)
    		}
    	}
    
    	val results = mutableListOf<List<T>>()
    
    	getAllSubsetsRecursive(
    		this,
    		mutableListOf(),
    		size - 1,
    		0,
    		results
    	)
    
    	return results.toList()
    }
    it does the job, however this still feels a bit verbose and messy to me, especially considering how often I create a copy of a list. is there any cleanup potential here?
    d
    m
    • 3
    • 16
  • s

    Sebouh Aguehian

    01/11/2020, 6:32 PM
    For a map backed property, I’m able to return null. I’m wondering if this is normal/expected.
    class MyClass {
        val map = mutableMapOf<String, Any?>().withDefault { null }
        var name: String by map
    }
    I cannot set
    name
    to
    null
    , but getting it returns
    null
    . This seems strange, given that the property has type
    String
    and not
    String?
    . Also, the IDE tells me the question mark in
    name?.toString()
    is unnecessary.
    t
    l
    +2
    • 5
    • 6
Powered by Linen
Title
s

Sebouh Aguehian

01/11/2020, 6:32 PM
For a map backed property, I’m able to return null. I’m wondering if this is normal/expected.
class MyClass {
    val map = mutableMapOf<String, Any?>().withDefault { null }
    var name: String by map
}
I cannot set
name
to
null
, but getting it returns
null
. This seems strange, given that the property has type
String
and not
String?
. Also, the IDE tells me the question mark in
name?.toString()
is unnecessary.
t

Tesserakt

01/11/2020, 6:34 PM
Method
toString
defined for all types - nullable or not
s

Sebouh Aguehian

01/11/2020, 6:37 PM
Indeed. Actual, my use case is not a String type, but an Android notification. Doing something like
notification?.icon
, the IDE tells me the question mark is unnecessary
l

LastExceed

01/11/2020, 6:40 PM
a non-nullable variable being null definitely shouldn't be possible. report on youtrack
j

James Richardson

01/11/2020, 9:20 PM
Null and non-null only works if everybody collaborates though. Android in particular has a habit of making things null at various times... the lifecycle is particularly important. I would ask on #android as they may have more specific knowledge...
e

E.Kisaragi

01/12/2020, 8:03 AM
in your project: NotNull and checked in Compilation time out of your reach: may let your NotNull be null
s

Sebouh Aguehian

01/12/2020, 3:12 PM
Looks like it’s already been reported: https://youtrack.jetbrains.com/issue/KT-27498
View count: 4