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
getting-started
  • f

    frank

    09/26/2022, 9:46 PM
    I want reduce this code, merging
    vidID
    and
    idMissing
    in a single variable.
    data class File22(val fileName: String, val vidID: Int = - 1)
    
    val files22 = ..... // Intance of 'File22'
    
    val vidID     = files22.map { it.vidID } // Array of Int e.g: [1,3,4,7]
    val idMissing = vidID.filterIndexed { index, i -> !vidID.contains(index)} // Result: idMissing -> 2,5,6
  • c

    Christian Lippka

    09/26/2022, 9:51 PM
    Question about inheritance and parameters
    import kotlinx.serialization.Serializable
    
    @Serializable
    abstract class TagsDto( val id: String?, val name: String, val icon: String?, val color: String? )
    
    @Serializable
    class LocationTagsDto( id: String? = null, name: String, icon: String?, color: String? )
        : TagsDto( id = id, name = name, icon = icon, color = color)
    This fails compilation on the second
    @Serializable
    This class is not serializable automatically because it has primary constructor parameters that are not properties
    I don’t want to have
    LocationTagsDto
    add any new property to
    TagsDto
    . How can I make this work? Thanks in advance.
    h
    2 replies · 2 participants
  • l

    Loney Chou

    09/27/2022, 1:12 AM
    Because your
    on
    function is not inline, that lambda is considered as a closure, and because closure is self-contained, it must "capture" stuff in the outer scope, and now that it's not possible to directly modify a local variable in a closure, that local is wrapped into an object with a var member for the closure to "modify".
    y
    7 replies · 2 participants
  • g

    Giuliopime

    09/27/2022, 7:46 AM
    Is there a way I can extract those validate blocks into a reusable function?
    fun Application.configureValidator() {
        install(RequestValidation) {
            validate<ClientUserDto> {
                val validationResult = it.validate(it)
                if (validationResult is Valid)
                    ValidationResult.Valid
                else
                    ValidationResult.Invalid(
                        validationResult.errors.map { error ->  "${error.dataPath} ${error.message}" }
                    )
            }
    
            validate<ClientListDto> {
                val validationResult = it.validate(it)
                if (validationResult is Valid)
                    ValidationResult.Valid
                else
                    ValidationResult.Invalid(
                        validationResult.errors.map { error ->  "${error.dataPath} ${error.message}" }
                    )
            }
    
            validate<ClientListItemDto> {
                val validationResult = it.validate(it)
                if (validationResult is Valid)
                    ValidationResult.Valid
                else
                    ValidationResult.Invalid(
                        validationResult.errors.map { error ->  "${error.dataPath} ${error.message}" }
                    )
            }
        }
    }
    r
    5 replies · 2 participants
  • t

    Tech

    09/27/2022, 11:25 AM
    Hey! I was wondering if it was possible to automatically cast a sealed class to one of it's children if a certain condition is met.
    sealed class Response(val success: Boolean) {
        class Success : Response(true)
        class Failure : Response(false)
    }
    So from this I'd like to do this.
    // Example
    val res = Response(true)
    
    if(res.success) {
      // cast to Response.Success
    } else {
      // cast to Response.Failure
    }
    I know I can probably just use the
    is
    clause but I think it'd be a tad bit nicer to do it like this, if it's not possible I'll just use
    is
    . Thanks in advance!
    s
    e
    9 replies · 3 participants
  • j

    João Gabriel Zó

    09/27/2022, 6:24 PM
    what does
    interface.()
    mean? e.g.
    interface.() -> Unit
    e
    1 reply · 2 participants
  • p

    poohbar

    09/27/2022, 7:11 PM
    I thought Kotlin keywords are soft keywords and context-specific?
    data class MyDataClass(
        val package: String, // error
        val hello: String
    )
    m
    b
    2 replies · 3 participants
  • m

    martmists

    09/27/2022, 8:21 PM
    Is there a way to check if a given KClass extends another KClass? I saw isSubclassOf but that doesn't exist in Kotlin/Native it seems If no good way to do that exists, is there a way to easily define structs that can automatically be converted to a ByteArray?
    r
    2 replies · 2 participants
  • s

    Stefan Oltmann

    09/28/2022, 3:10 PM
    Can I use the UInt class to make this easier to read?
    private fun getUInt16(firstByte: Byte, secondByte: Byte): Int =
        firstByte.toInt() shl 8 and 0xFF00 or (secondByte.toInt() and 0xFF)
    r
    k
    +1
    14 replies · 4 participants
  • s

    sarvagya agarwal

    09/28/2022, 4:50 PM
    How can I read multiple files concurrently using coroutines ? I did this but the IDE throws me a warning saying
    inappropriate blocking method call
    for
    FileInputStream
    and
    read
    functions.
    suspend fun uploadFiles(files: List<File>, convertToPdf: Boolean): List<String> = coroutineScope {
    	return@coroutineScope files.map {
    		async {
    			uploadFile(it, convertToPdf)
    		}
    	}.awaitAll()
    }
    	
    @Throws(IOException::class, FileNotFoundException::class)
    suspend fun uploadFile(file: File, convertToPdf: Boolean): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    	val chunk = ByteArray(4096)
    	val inputStream = FileInputStream(file)
    	val res: Flow<FileChunk> = flow {
    		while(true) {
    			val size = inputStream.read(chunk)
    			if(size <= 0) break
    			val fileChunk = FileChunk.newBuilder().setConvertToPdf(convertToPdf)
    				.setChunk(ByteString.copyFrom(chunk, 0, size)).build()
    			emit(fileChunk)
    		}
    	}
    	val response = blockingStub.uploadFiles(res)
    	return@withContext "Some String"
    }
  • p

    Paul Griffith

    09/28/2022, 5:20 PM
    Recognizing this is generally a bad idea… is there any way to force the compiler to allow me to pass a null value into a Java method with a parameter annotated as
    @Nonnull
    ?
    c
    e
    +2
    8 replies · 5 participants
  • t

    Tech

    09/28/2022, 10:22 PM
    Hey! I was wondering if it was possible to possibly use contracts to cast data as not null as long as the type does not equal Unit. I use
    Unit
    to represent when an action has been preformed but no data is returned, so if it's anything but unit then there's data in the class.
    sealed class Test<out T>(val success: Boolean) {
      abstract val data: T?
    
      class A<out T>(override val data: T?) : Test(true)
      class B<out T>(override val data: T?) : Test(false)
    }
    
    fun Test<Any>.isSuccess(): Boolean {
      contract {
        returns(true) implies(this@isSuccess is Test.A)
        // if T != Unit then data != null
      }
      return this is Test.A
    }
    y
    1 reply · 2 participants
  • d

    Daniel Zhang

    09/28/2022, 11:40 PM
    What is the proper way to use Flow to run tasks for a given amount of time while also utilizing rate limiting? I have the following:
    runBlocking {
        withTimeoutOrNull(1000) {
            inputs.asSequence().repeat().asFlow()
                .rateLimiter(rateLimiter)
                .map { executeInput(it) }
                .toList()
        }
    }
    
    val rateLimiter = RateLimiter.of(
        properties.name,
        RateLimiterConfig
            .custom()
            .limitForPeriod(properties.rateLimiter.limitForPeriod)
            .limitRefreshPeriod(properties.rateLimiter.limitRefreshPeriod)
            .timeoutDuration(properties.rateLimiter.timeoutDuration)
            .build()
    )
    
    /**
     * @see <a href="<https://stackoverflow.com/questions/48007311/how-do-i-infinitely-repeat-a-sequence-in-kotlin>">Infinite Sequence</a>
     */
    private fun <T> Sequence<T>.repeat() = sequence { while (true) yieldAll(this@repeat) }
    Here I’m attempting to turn a list of inputs into an infinite sequence that I can then throttle with a RateLimiter + time out after a certain duration, but neither seem to be working.
    1 reply · 1 participant
  • h

    Hassaan

    09/29/2022, 9:22 AM
    can anybody tell me ‘scanner.nextInt( )’ equivalent in kotlin without using scanner class
    k
    2 replies · 2 participants
  • o

    Olayinka Koleaje

    09/29/2022, 12:27 PM
    👋 Hello, team!
  • k

    Klitos Kyriacou

    09/29/2022, 2:41 PM
    I want to pass a parameter to a function (actually a super class constructor call), and this parameter is a complicated expression and I tried using
    run { ... }
    . However,
    run
    is overloaded as both an extension and non-extension function. Since the context includes an implicit "this" receiver, Kotlin favours calling the extension version. How can I force it to run the non-extension version?
    e
    r
    3 replies · 3 participants
  • d

    Daniel Felipe Henao Toro

    09/29/2022, 5:49 PM
    I have a question please, I'm trying to fix the highlighted line, but I don´t achieve to fix it. The suggestion from IntelliJ is to put
    root.<String>get("codes")
    but it always shows me another failure, does someone know about JPA Specification that you can help me?
    g
    2 replies · 2 participants
  • m

    Meherdatta Chepuri

    09/29/2022, 7:06 PM
    👋 Hello, team! What would be the recommended approach to set up the KMM project and repo? Is it better to have iOS and Android apps in the same repo along with the shared module or is it better to separate them out? wanted to check the experience so far from the community with different approaches. Curious to hear some great use-cases!
  • p

    Pavan Badugucse

    09/29/2022, 9:53 PM
    hey hi need some help on setting kotlin exposed framework transaction isolation level to 2 (read committed ) from level 4 globally..
    1 reply · 1 participant
  • r

    rrva

    09/30/2022, 10:01 AM
    what can I use to serialize a data class to compilable kotlin code? Just toString() and some manual editing? Is there something nice?
    m
    j
    +2
    32 replies · 5 participants
  • o

    oday

    09/30/2022, 10:58 AM
    can I not have a map of String, Array<String> ?
    val technologies = mapOf<String, Array<String>>("Jetpack Compose", arrayOf("Compose"))
    2 replies · 1 participant
  • o

    oday

    09/30/2022, 12:58 PM
    for (j in 0 until pdfReader.numberOfPages) {
                    extractedText += PdfTextExtractor.getTextFromPage(pdfReader, j + 1)
    
                    technologies.forEach { (key, values) ->
                        values.map {
                            if (extractedText.contains(it, ignoreCase = true)
                                || extractedText.contains("${it}s", ignoreCase = true)
                            ) {
                                occurrences[key] = occurrences.getOrDefault(key, 0) + 1
                            }
                        }
                    }
                }
    
                println(occurrences)
                val person = extractedText.split(" ")[0].trim { it == ',' }
                results[person] = occurrences
    I would like to clear
    occurrences
    after I’m done with it so that I can load it again with new values after I insert it into
    results[person]
    but doing that is causing it to store an empty map into `results[person]`…
    m
    5 replies · 2 participants
  • t

    Tim Schraepen

    09/30/2022, 1:43 PM
    In Book.kt:
    
    data class Book(val isbn: ISBN, val title: Title)
    @JvmInline value class ISBN(val value: String)
    @JvmInline value class Title(val value: String)
    
    Somewhere in BookDAO.java:
    new Book("123","Thundercats");
    When I'm looking at the code in IntelliJ, it's simply compiling (no red squiggly lines). When I run a
    mvn clean install
    it also just compiles. But when I do a build (ctrl+F9), I'm getting this:
    java: Book(java.lang.String,java.lang.String) has private access in Book
    When I define book as
    data class Book(val isbn: String, val title: String)
    compilation does succeed. What is going on? It smells like intelliJ is using an older Kotlin version to compile or something? In the build output I'm getting this:
    ...
    Kotlin: kotlinc-jvm 1.7.20 (JRE 17.0.2+8)
    ...
    javac 11.0.9 was used to compile java sources
    I'd like to try to get kotlinc-jvm to use JRE 11 to compile, but don't know how.
    e
    5 replies · 2 participants
  • s

    sarvagya agarwal

    09/30/2022, 3:17 PM
    Is there a cleaner way to do this ?
    var firstChunk = true
    val fileChunks = flow {
    	if(firstChunk) {
    		val metadata = MetaData.newBuilder()
    			.setPath(file.path)
    			.setConvertToPdf(BoolValue.of(convertToPdf))
    			.build()
    		emit(FileUploadRequest.newBuilder().setMetadata(metadata).build())
    		firstChunk = false
    	} else {
    		while(true) {
    			val size = inputStream.read(chunk)
    			if(size <= 0) break
    			val fileChunk = FileChunk.newBuilder()
    				.setData(ByteString.copyFrom(chunk, 0, size)).build()
    			emit(FileUploadRequest.newBuilder().setContent(fileChunk).build())
    		}
    	}
    }
    Trying to create a flow of file bytes where the first byte is metadata of the file.
    r
    1 reply · 2 participants
  • j

    Jasmin Fajkic

    09/30/2022, 5:23 PM
    Hello guys. I am JS developer new in Kotlin world. Want to flatten list to single list. In JS i use simple recursive function that is seems does not work correctly. In thread is mock data how list looks like.
    3 replies · 1 participant
  • a

    Abdullah Samir

    09/30/2022, 11:49 PM
    Hello guys, i need to know why i need to create custom annotation in Kotlin? what is the benefit of creating custom annotation? Thank You
    c
    j
    +1
    7 replies · 4 participants
  • r

    Rohan Sanap

    10/02/2022, 6:54 AM
    I am a Swift developer learning Kotlin since last 2 days by following https://play.kotlinlang.org. I have doubt related to lambdas. Question - In Swift, we have a similar concept like lambda called as closure. But, they are distinctly differentiated when passing them into function arguments by marking them as
    @escaping
    or
    @non-escaping
    which denotes if they will be executed asynchronously or synchronously respectively. How do we differentiate between asynchronous or synchronous lambdas in Kotlin?
    s
    h
    +1
    4 replies · 4 participants
  • a

    Arimil

    10/03/2022, 2:00 PM
    Hey guys I'm trying to convert an odd lambda expression from a gradle plugin to Kotlin:
    project.getExtensions().configure(PublishingExtension.class, extension -> {
                extension.getPublications().registerFactory(MavenPublication.class, new MavenPublicationFactory(
                        dependencyMetaDataProvider,
                        instantiatorFactory.decorateLenient(),
                        fileResolver,
                        project.getPluginManager(),
                        project.getExtensions()));
                realizePublishingTasksLater(project, extension);
            });
    However I'm having issues with the syntax for this in Kotlin.
    r
    8 replies · 2 participants
  • z

    zt

    10/04/2022, 12:55 AM
    val values = match.groupValues.drop(1) // ["kotlin slack"]
    var newResponse = filter.response!! // "hi $1"
    values.forEachIndexed { index, value ->
        newResponse = filter.response!!.replace("\$$index", value)
    }
    
    // newResponse = "hi kotlin slack"
    Is there some cleaner way of doing this? I wanna replace
    $0
    ,
    $1
    ,
    $2
    , etc, with its corresponding value
    e
    m
    4 replies · 3 participants
  • s

    Slackbot

    10/04/2022, 12:21 PM
    This message was deleted.
Powered by Linen
Title
s

Slackbot

10/04/2022, 12:21 PM
This message was deleted.
View count: 4