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

    iamsteveholmes

    08/04/2022, 4:21 AM
    Shameless plug. I’m starting a series on youtube on Quarkus in Kotlin. I’d appreciate any comments in the comment section if you have suggestions:

    https://www.youtube.com/watch?v=NEc8PWNKlo0▾

    c
    k
    5 replies · 3 participants
  • k

    Kristian Nedrevold

    08/04/2022, 12:46 PM
    I am using ktor with ContentNegotiation. What is the idiomatic way to handle the unchecked exceptions you can get when retrieving a response using ktor client? example code
    val responseData: ReservedCitizenResponse = response.body()
    . If there is something wrong in the response body this will just crash with an JsonDecodingException as an unchecked exception. It would be nice if the .body() function returned a Result monad so you could handle the cases of successful and unsuccessful serialization.
    l
    2 replies · 2 participants
  • s

    Stylianos Gakis

    08/08/2022, 9:29 AM
    Question regarding logging, in the context of a Spring project, using SLF4J, Coroutines and Datadog, asking here to see if someone else has encountered this before. When logging our uncaught exceptions in normal non-coroutine code, the exception is logged by slf4j. The logs are picked up by a Datadog agent, and sent to Datadog. When the exception is shown in Datadog, it takes up one line in the logger, with the stacktrace placed in the log entry’s details. We recently added coroutines to this service, defining an
    ApplicationScope
    like
    class ApplicationScope(applicationScope: CoroutineScope) : CoroutineScope by applicationScope
    // Then provided like
    @Bean
    fun applicationScope(): ApplicationScope {
      return ApplicationScope(CoroutineScope(SupervisorJob() + <http://Dispatchers.IO|Dispatchers.IO>))
    }
    then converted an existing function to be fire-and-forget by using `launch`:
    fun doSomething(...) = applicationScope.launch {...}
    When an unhandled exception is thrown in the coroutine, somehow it doesn’t follow the normal logging/formatting process. Instead of a single error line in the log, we get each line in the stacktrace showing up as a separate line in the logs. This then shows up in the timeline as a whole lot of errors (50-100+) occurring at the same time. Has someone who uses this combination of coroutines-slf4j-datadog experienced this before? Could it be that the logger is not picking up these unhandled exceptions and it’s logging to the console? Or maybe we need to add something special to the
    ApplicationScope
    to get SLF4J/Datadog to parse/format this error properly?
    d
    2 replies · 2 participants
  • a

    Anshi

    08/16/2022, 1:19 PM
    Hello, I'm very noob for android development can anyone please tell me how to implement real api with @post method in my android studio with kotlin project.
    a
    2 replies · 2 participants
  • a

    August Lilleaas

    08/22/2022, 10:43 AM
    hi, folks! I have a question about
    is
    checks and delegation from a class to an object. Ktor has an extension function on
    ApplicationRequest
    that uses
    when(this)
    to check if the request
    is
    a
    ServletApplicationRequest
    . The problem is that the actual request object that I call the extension function on, is a
    RoutingApplicationRequest
    , which is a class that delegates to the original request object. Which in turn causes
    is ServletApplicationRequest
    to be false, as
    is
    only seems to check class inheritance hierarchies, and not delegation. Is there a way to work around this? Or is it an issue/bug that Ktor needs to handle differently to work as expected? FYI, here’s the full extension function:
    public val ApplicationRequest.javaSecurityPrincipal: Principal?
        get() = when (this) {
            is ServletApplicationRequest -> servletRequest.userPrincipal
            else -> null
        }
    and here’s the class that the instance of the request object is a member of:
    public class RoutingApplicationRequest(
        override val call: RoutingApplicationCall,
        override val pipeline: ApplicationReceivePipeline,
        request: ApplicationRequest
    ) : ApplicationRequest by request
    e
    4 replies · 2 participants
  • r

    rrva

    08/24/2022, 3:06 PM
    Does @JvmRecord give any performance benetfits? For example around heap footprint, object equality/hashcode etc?
    l
    2 replies · 2 participants
  • d

    DavdF

    08/24/2022, 4:26 PM
    Hello all!
  • s

    Slackbot

    08/24/2022, 10:43 PM
    This message was deleted.
    d
    d
    +2
    11 replies · 5 participants
  • p

    Paresh Prajapati

    08/30/2022, 10:34 AM
    How can we read config data into code from custom properties file and assigning this values in application.conf?
  • p

    Paresh Prajapati

    08/30/2022, 10:35 AM
    Please assist me. I'm receiving a parsing error when I try to read from application.conf into the code.
  • p

    Paresh Prajapati

    08/30/2022, 10:36 AM
    Error - Property 'ktor.database.url' not found and throwing applicationconfigurationexception
  • r

    Ricardo Fernandes

    09/01/2022, 7:20 PM
    Hello guys! looking for tips and tricks for using kotlin native/JVM on AArch64 for backend systems/microservices
    e
    j
    +2
    11 replies · 5 participants
  • y

    Yogeshvu

    09/02/2022, 3:53 PM
    Looking for suggestions on Coroutines book for server side applications (Non-Android platform). Any book which you would recommend here. thanks..
    d
    p
    3 replies · 3 participants
  • a

    Abdullah Samir

    09/06/2022, 11:52 AM
    hello i work on spring boot app using Kotlin lang if the HTTP method is GET and i request the endpoint with POST method it throw server error, so how to catch this error and throw runtime error instead. thank's
    u
    a
    3 replies · 3 participants
  • c

    Carlos Valencia

    09/16/2022, 6:40 AM
    Hi. I am new to Ktor and I have a problem. My problem is that items in database have a numeric id that needs to be increase by one each request. Right now if I receive 2 or more requests at the same time they query the same last item from database having the same item. I need to wait until the first request is completed before accepting a new one, so I can keep the correct order in the database. Something like a request queue or Channel or similar. So, my question is. How can I make the pipeline sequencial? and wait until it is completed before starting a new one?
    j
    r
    5 replies · 3 participants
  • a

    Andrew Louis

    09/16/2022, 2:31 PM
    Cross-posting this here in case you folks have some insight 🙂 https://kotlinlang.slack.com/archives/C1CFAFJSK/p1663212895400299
    a
    4 replies · 2 participants
  • m

    Milton Johansson

    09/20/2022, 6:17 AM
    Hey Hellu! Thank you so much for accepting me. I am pretty new at Kotlin and is working with a ktor-app right now. I have not built it from the beginning but I have the main responsibility of the application. We have some tests in the application but I wanted to higher the test-coverage by using externalServices but the problem is that I get DuplicatePluginException on io.ktor.server.plugins.contentnegotiation.ContentNegotiation because both the mock-server and my application uses the same plugin. I have tried everything I can think of and that the internet provided to me but nothing works. Can someone please help me, have som kotlin-experts in the team but they are also out of ideas :-(
    p
    2 replies · 2 participants
  • s

    Slackbot

    09/25/2022, 2:53 PM
    This message was deleted.
    d
    1 reply · 2 participants
  • e

    Erik Dreyer

    09/27/2022, 7:05 PM
    I’m having a bit of trouble with the type system. Anyone able to help me resolve this? The idea is that the type defined by the variable
    e
    in the
    main()
    function determines the return type of the
    dispatch()
    function. The error I’m getting is:
    Type mismatch.
    Required:
      Result<E>
    Found:
      Result<ExampleEvent>
    b
    d
    +1
    24 replies · 4 participants
  • b

    Bence Erős

    10/02/2022, 5:57 PM
    Hello, what is the best practice to implement assertions in unittests written in kotlin? JUnit's built-in Assertions? AssertJ? Hamcrest? Kotest?
    d
    h
    +11
    22 replies · 14 participants
  • y

    Yogeshvu

    10/07/2022, 4:59 PM
    I would like to retrieve response body message for a given 400 status code when using the spring webclient. However, I can only find the error code and not the actual error message contained in the code. I am using following snippet. how to actually extract the response body in the 400 status response .
    val retrievedResource: Mono<String> = myRequest
                .retrieve()
                .onStatus(HttpStatus::is4xxClientError) { Mono.error(RuntimeException("4XX Error ${it.statusCode()}, ${it.bodyToMono(String::class.java)}")) }
                .onStatus(HttpStatus::is5xxServerError) { Mono.error(RuntimeException("5XX Error ${it.statusCode()}, ${it.bodyToMono(String::class.java)}")) }
            .bodyToMono(String::class.java)
            return retrievedResource.share().block()
  • j

    João Esperancinha

    10/11/2022, 6:13 PM
    Hey people!, Anyone knows how to get an SQL connection to PostgresSQL via Kotlin Native? I'm scrambling to get this done and I'm, already looking at the possibility of calling postgress command natively by making my own library, but maybe I'm just missing some easier solution?
    h
    j
    +1
    5 replies · 4 participants
  • a

    Abdullah Samir

    10/13/2022, 4:22 PM
    Please Simple Question: where is the code stored after jvm work and loaded the needed classes, are the instruction set in the stack or where?
    v
    3 replies · 2 participants
  • p

    Paresh Prajapati

    10/14/2022, 12:09 PM
    Hello friends, Do anyone know how can I load file which is there in resource folder in ktor?
    r
    2 replies · 2 participants
  • o

    Oleg Shuliak

    10/18/2022, 6:41 AM
    hey everyone. Got a question about the better implementation of the function, maybe someone could assist. I have a function that should return different Response based on the received data from the
    workflowService.findByCompanyId
    , that returns data class:
    data class WorkflowWithStatusLookup(val workflow: Workflow, val status: Result<WorkflowStatus>)
    also, I’d like to log the exception based on the “invalid” result of the status. Here is want I’ve came up with, but I’m pretty sure it’s not optimal way
    override fun listWorkflow(featureToggles: FeatureToggles): ResponseEntity<GetWorkflowsResponse> {
            return runBlocking(requestContext.coroutineContext) {
                val (valid, invalid) = workflowService.findByCompanyId(getCompanyId(), featureToggles)
                    .partition { it.status.isSuccess }
                val apiResponseModel = valid.map {
                    it.workflow.toWorkflowInfoResponse(it.status.getOrThrow())
                }
                return@runBlocking if (invalid.isEmpty()) {
                    ResponseEntity(
                        GetWorkflowsResponse(
                            data = apiResponseModel
                        ),
                        HttpStatus.OK
                    )
                } else {
                    ResponseEntity(
                        GetWorkflowsResponse(
                            data = apiResponseModel,
                            meta = invalid.map { it.workflow.name }
                        ),
                        HttpStatus.PARTIAL_CONTENT
                    ).also {
                        invalid.forEach {
                            throw FormNotFound(
                                it.workflow.definition.trigger.entityId!!.toString(),
                                it.workflow.companyId
                            )
                        }
                    }
                }
            }
        }
    r
    1 reply · 2 participants
  • j

    Justin Xu

    10/19/2022, 4:47 AM
    For Realm Kotlin sdk, is there a simple way to serialize ObjectId? The ObjectId itself is an interface while the actual object to be serialized is ObjectIdImpl, so I always get the error
    ObjectIdImpl is not registered for polymorphic serialization in the scope of ObjectId
    when using a custom serializer
  • s

    Simon

    10/19/2022, 6:27 PM
    Hey people, in case you are curious how to use JOOQ with Spring, Arrow in a reactive way using coroutines, please take a look at my example repository at: https://github.com/sbuettner/reactive-database-access-kotlin Its very small and hopefully approachable repository with some documentation for people interested in this topic. Feedback appreciated.
  • a

    Avi Perl

    10/27/2022, 8:07 PM
    Would it be possible / realistic to serialize and un-serialize an exception?
    e
    c
    7 replies · 3 participants
  • m

    mike.holler

    10/28/2022, 4:08 PM
    Hey all, I have a question about precompiled strings that I'd like to be able to use in annotations (so they must be
    const val
    and cannot be
    val
    ). Does anybody have any suggestions? The test below fails right now, but I'd like to make it pass by only adding code. I'd love to use
    .trimIndent()
    when declaring
    myString
    but I can't. Is there something I can use that the compiler will unfold?
    const val myString = """
        This is my string. I wrap it across multiple lines when it
        becomes too long, but there should be no lines visible when
        using this string. In other words, the newlines should be
        compiled out of this string, and the margin collapsed. Is
        there any compiler plugin I can use that can help make this
        a reality?
    """
    
    class ExampleTest {
        @Test
        fun `precompiled multi-line string has no newlines`() {
            expectThat(myString).doesNotContain('/n')
        }
    }
    v
    k
    2 replies · 3 participants
  • e

    Eli

    10/29/2022, 10:41 AM
    Hello! Is it possible to have a custom plugin act as a “middleware” that can abort the whole pipeline(the request) ? Our use-case: After the “validate { }” function, we need to check whether our user has “profile completed” status (by checking his claims on the JWT), and if not - respond with some status. But validate itself only has 2 options (if principal is null -> it returns 401, otherwise it just proceeds). And if I implement a custom plugin, even if I do there “call.respond(..)” it still proceeds to other plugins instead of finishing the whole pipeline I elaborated more on it here : https://stackoverflow.com/questions/74243213/how-to-stop-pipeline-in-ktors-plugins-middleware-that-sends-a-response-and-abo
    r
    3 replies · 2 participants
Powered by Linen
Title
e

Eli

10/29/2022, 10:41 AM
Hello! Is it possible to have a custom plugin act as a “middleware” that can abort the whole pipeline(the request) ? Our use-case: After the “validate { }” function, we need to check whether our user has “profile completed” status (by checking his claims on the JWT), and if not - respond with some status. But validate itself only has 2 options (if principal is null -> it returns 401, otherwise it just proceeds). And if I implement a custom plugin, even if I do there “call.respond(..)” it still proceeds to other plugins instead of finishing the whole pipeline I elaborated more on it here : https://stackoverflow.com/questions/74243213/how-to-stop-pipeline-in-ktors-plugins-middleware-that-sends-a-response-and-abo
r

Ron S

10/29/2022, 10:56 AM
I'm no expert, but I could imagine that the rest of the pipeline is aborted when response.pipeline.execute is called. So, try calling call.respond instead of just setting the status code.
e

Eli

10/29/2022, 11:04 AM
Hi Ron, Yes that’s what I’m doing : “call.respond” (** we use “call.respondWith(..)” which is some extension we made that wraps the “call.respond”) I think there’s “finish()” function on the pipeline, but I can’t seem to have any access to it from the custom Plugins or even the “validate” block.
r

Ron S

10/29/2022, 11:15 AM
I thought the wrapper only sets the response code and thus not invokes pipeline.execute. I'm afraid I can't help you then.
View count: 13