https://kotlinlang.org logo
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
benchmarks
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
confetti
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
hiring-french
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
lincheck
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
Title
c

Chad Gregory

02/06/2023, 1:21 PM
I have a serializable data class that I am using with ktor client
@Serializable
data class Job (
    val information: JobInformation = JobInformation(),
    val additional: AdditionalInformation = AdditionalInformation(),
    val bom: PersistentList<BOM> = persistentListOf()
)

@Serializable
data class BOM(
    @SerialName("comp_item")
    val compItem: String = "",
    val sequence: String = "",
    @SerialName("comp_qty")
    val compQty: String = "",
    @SerialName("comp_uom")
    val compUom: String = "",
    val operation: String = "",
    val type: String = ""
)
but when ktor client tries to decode the data from the request response I get this error
kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject (Kotlin reflection is not available) as the serialized body of kotlinx.serialization.Polymorphic<PersistentList>, but had class kotlinx.serialization.json.JsonArray (Kotlin reflection is not available)
I understand what the error is saying but I don't know how to fix it.
a

Adam S

02/06/2023, 2:53 PM
is
PersistentList
from kotlinx.collections? Have you set up custom serializers? https://github.com/Kotlin/kotlinx.collections.immutable/issues/63
c

Chad Gregory

02/06/2023, 4:06 PM
First I would like to know how a first party package is missing serialization support for 3 years but I'm just going to table that for now. I created this
@Serializer(forClass = PersistentList::class)
class PersistentListSerializer<T>(private val dataSerializer: KSerializer<T>) : KSerializer<PersistentList<T>> {
    private class PersistentListDescriptor<T> : SerialDescriptor by serialDescriptor<List<T>>() {
        @ExperimentalSerializationApi
        override val serialName: String = "kotlinx.serialization.immutable.persistentList"
    }
    override val descriptor: SerialDescriptor = PersistentListDescriptor<T>()
    override fun serialize(encoder: Encoder, value: PersistentList<T>) {
        return ListSerializer(dataSerializer).serialize(encoder, value.toList())
    }
    override fun deserialize(decoder: Decoder): PersistentList<T> {
        return ListSerializer(dataSerializer).deserialize(decoder).toPersistentList()
    }
}
Switched with Kapt to KSP because of this stupid error https://github.com/Kotlin/kotlinx.serialization/issues/1908#issuecomment-1105187175 but now I am getting a new error
E  FATAL EXCEPTION: main
                                                                                                    Process: com.example.testapp, PID: 22633
                                                                                                    java.lang.IllegalStateException: Only KClass supported as classifier, got T
                                                                                                    	at kotlinx.serialization.internal.Platform_commonKt.kclass(Platform.common.kt:102)
                                                                                                    	at kotlinx.serialization.SerializersKt__SerializersKt.serializerByKTypeImpl$SerializersKt__SerializersKt(Serializers.kt:78)
                                                                                                    	at kotlinx.serialization.SerializersKt__SerializersKt.serializer(Serializers.kt:59)
                                                                                                    	at kotlinx.serialization.SerializersKt.serializer(Unknown Source:1)
                                                                                                    	at kotlinx.serialization.SerializersKt__SerializersKt.builtinSerializer$SerializersKt__SerializersKt(Serializers.kt:96)
                                                                                                    	at kotlinx.serialization.SerializersKt__SerializersKt.serializerByKTypeImpl$SerializersKt__SerializersKt(Serializers.kt:84)
                                                                                                    	at kotlinx.serialization.SerializersKt__SerializersKt.serializer(Serializers.kt:59)
                                                                                                    	at kotlinx.serialization.SerializersKt.serializer(Unknown Source:1)
                                                                                                    	at kotlinx.serialization.SerializersKt__SerializersKt.serializer(Serializers.kt:41)
                                                                                                    	at kotlinx.serialization.SerializersKt.serializer(Unknown Source:1)
                                                                                                    	at ca.on.listech.imm.util.PersistentListSerializer$PersistentListDescriptor.<init>(PersistentListSerializer.kt:31)
                                                                                                    	at ca.on.listech.imm.util.PersistentListSerializer.<init>(PersistentListSerializer.kt:22)
                                                                                                    	at ca.on.listech.imm.domain.models.Job$$serializer.childSerializers(Job.kt:10)
                                                                                                    	at kotlinx.serialization.internal.PluginGeneratedSerialDescriptor$childSerializers$2.invoke(PluginGeneratedSerialDescriptor.kt:36)
                                                                                                    	at kotlinx.serialization.internal.PluginGeneratedSerialDescriptor$childSerializers$2.invoke(PluginGeneratedSerialDescriptor.kt:36)
                                                                                                    	at kotlin.SafePublicationLazyImpl.getValue(LazyJVM.kt:107)
                                                                                                    	at kotlinx.serialization.internal.PluginGeneratedSerialDescriptor.getChildSerializers(PluginGeneratedSerialDescriptor.kt:36)
                                                                                                    	at kotlinx.serialization.internal.PluginGeneratedSerialDescriptor.getElementDescriptor(PluginGeneratedSerialDescriptor.kt:76)
                                                                                                    	at kotlinx.serialization.descriptors.SerialDescriptorKt$elementDescriptors$1$1.next(SerialDescriptor.kt:284)
                                                                                                    	at kotlinx.serialization.descriptors.SerialDescriptorKt$elementDescriptors$1$1.next(SerialDescriptor.kt:279)
                                                                                                    	at kotlinx.serialization.internal.PluginGeneratedSerialDescriptorKt.hashCodeImpl(PluginGeneratedSerialDescriptor.kt:137)
                                                                                                    	at kotlinx.serialization.internal.PluginGeneratedSerialDescriptor$_hashCode$2.invoke(PluginGeneratedSerialDescriptor.kt:44)
                                                                                                    	at kotlinx.serialization.internal.PluginGeneratedSerialDescriptor$_hashCode$2.invoke(PluginGeneratedSerialDescriptor.kt:44)
                                                                                                    	at kotlin.SafePublicationLazyImpl.getValue(LazyJVM.kt:107)
                                                                                                    	at kotlinx.serialization.internal.PluginGeneratedSerialDescriptor.get_hashCode(PluginGeneratedSerialDescriptor.kt:44)
                                                                                                    	at kotlinx.serialization.internal.PluginGeneratedSerialDescriptor.hashCode(PluginGeneratedSerialDescriptor.kt:97)
                                                                                                    	at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:936)
                                                                                                    	at kotlinx.serialization.json.internal.DescriptorSchemaCache.get(SchemaCache.kt:35)
                                                                                                    	at kotlinx.serialization.json.internal.DescriptorSchemaCache.getOrPut(SchemaCache.kt:27)
                                                                                                    	at kotlinx.serialization.json.internal.JsonNamesMapKt.getJsonNameIndex(JsonNamesMap.kt:52)
                                                                                                    	at kotlinx.serialization.json.internal.StreamingJsonDecoder.decodeObjectIndex(StreamingJsonDecoder.kt:139)
                                                                                                    	at kotlinx.serialization.json.internal.StreamingJsonDecoder.decodeElementIndex(StreamingJsonDecoder.kt:92)
                                                                                                    	at ca.on.listech.imm.domain.models.Job$$serializer.deserialize(Job.kt:10)
                                                                                                    	at ca.on.listech.imm.domain.models.Job$$serializer.deserialize(Job.kt:10)
                                                                                                    	at kotlinx.serialization.json.internal.PolymorphicKt.decodeSerializableValuePolymorphic(Polymorphic.kt:59)
                                                                                                    	at kotlinx.serialization.json.internal.StreamingJsonDecoder.decodeSerializableValue(StreamingJsonDecoder.kt:36)
                                                                                                    	at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableValue(AbstractDecoder.kt:43)
                                                                                                    	at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableElement(AbstractDecoder.kt:70)
a

Adam S

02/06/2023, 4:08 PM
@Serializer(forClass = PersistentList::class)
class PersistentListSerializer<T>(private val dataSerializer: KSerializer<T>)
annotating it with
@Serializer
probably isn’t right
normally
@Serializer(forClass ...)
is used on independent objects
are you sure you need to serialize directly to/from
PersistentList
? What if you used a regular list, and then converted it via a property?
@Serializable
data class X(
   private val boms: List<BOM>
) {
  val bomsPersistent = boms.toPersistentList()
}
(tweak it to make it more accurate/a bit prettier)
c

Chad Gregory

02/06/2023, 4:13 PM
that might be the a better idea, this is getting kind of ridiculous lol
a

Adam S

02/06/2023, 4:16 PM
yeah KxS can be complicated - it’s usually easier to have a little bit of extra Kotlin code, because it’s easier to understand and debug
c

Chad Gregory

02/06/2023, 4:46 PM
I am using this with Datastore, would there be any issue with retrieving bom from a DataStore as a Flow<Job>?
val getJob: Flow<Job> = cxt.job.data

suspend fun updateActiveJob(info: JobInformation, additional: AdditionalInformation, bom: List<BOM>) {
        cxt.job.updateData {job ->
            job.copy(
                information = info,
                additional = additional,
                bom = job.bomList.mutate {
                    for (item in bom) {
                        it.add(item)
                    }
                }
            )
        }
    }
a

Adam S

02/06/2023, 4:50 PM
sorry I don’t really understand the context. Are you asking if you can use KxS to encode/decode data on the fly? Because that’s fine
c

Chad Gregory

02/06/2023, 4:52 PM
my question is since I made this change
@Serializable
data class X(
   private val bom: List<BOM>
) {
  val bomList = bom.toPersistentList()
}
will there be an issue with getting the data out of the datastore via a Flow when the serializable data class does not have a PersistentList property?
a

Adam S

02/06/2023, 4:56 PM
that depends on a lot of things! All KxS cares about is that 1. everything has a KSerializer and SerialDescriptor, and 2. the property
bom
is structured like a list
for example, if it’s JSON data then KxS doesn’t care if it’s deserializing to a List or an Array or ArrayList or MutableList
c

Chad Gregory

02/06/2023, 4:59 PM
Well the DataStore contains a PersistentList<BOM> which then needs to become a List<BOM> so my guess is that would be an issue since I had issues going from List<BOM> to PersistentList<BOM>\
if so there basically no point to even use PersistentList at all and just store it as json data for something
a

Adam S

02/06/2023, 5:01 PM
that could well be. I’ve never used the kotlinx.collections so I wouldn’t know
c

Chad Gregory

02/06/2023, 5:01 PM
well with the context of this thread that would be true