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
stdlib
  • h

    hmole

    09/21/2018, 6:49 AM
    Is there a way to make a generic lamda reference? Something like
    thing.map(otherThing::method<MyType>)
    . I've tried putting brackets everywhere and it doesn't work ☹️
    k
    l
    • 3
    • 2
  • v

    vmichalak

    09/21/2018, 1:06 PM
    Hi guys, anyone know the reason why Int.pow(int) doesn't exists in Kotlin & Java ?
    k
    s
    +2
    • 5
    • 14
  • a

    anstaendig

    09/23/2018, 5:13 PM
    Shouldn’t be too hard to implement them yourself?
    l
    • 2
    • 1
  • j

    jw

    09/24/2018, 6:13 PM
    I don't like that this makes it extremely easy to use the worst possible serialization format
    👆 4
    ➕ 5
    e
    f
    +3
    • 6
    • 10
  • e

    elect

    10/10/2018, 12:46 PM
    what about
    iterator()
    on `Enum`s, so that we can write
    for(e in enum)
    ? Instead of
    e in enum.values()
    which, I guess, implies an array copy?
    m
    • 2
    • 5
  • m

    miha-x64

    10/10/2018, 1:49 PM
    Shouldn't
    public operator fun <T> Array<T>.plus(elements: Array<out T>): Array<T>
    have
    out
    receiver variance?
    enum class A { A }
    enum class B { B }
    val sum = A.values() + B.values()
    
    // adding the following function makes the code above work:
    private inline operator fun <reified T> Array<out T>.plus(elements: Array<out T>): Array<T> {
        val sum = arrayOfNulls<T>(size + elements.size)
        System.arraycopy(this, 0, sum, 0, size)
        System.arraycopy(elements, 0, sum, size, elements.size)
        return sum as Array<T>
    }
    d
    i
    • 3
    • 8
  • h

    Hamza

    10/10/2018, 2:42 PM
    is there a good class or a package with a bunch of extention functions in the stdlib? I want to show how they are used in the sdk and i would like good examples
    i
    e
    • 3
    • 5
  • g

    ghedeon

    10/11/2018, 3:04 PM
    Any particular reason for not having
    Arrays.binarySearch() /  IntArray.binarySearch()
    that accepts comparator argument? The way it works now, it's possible to perform a
    binarySearch
    in an ascending
    IntArray
    but not in a descending. At the same time, no problems with
    Array<Int>
    .
    k
    • 2
    • 4
  • l

    littlelightcz

    10/11/2018, 7:10 PM
    BTW is there curretly any discussion going on about adding some convenience extension functions on e.g.
    List<Result<T>>
    (when using
    runCatching {}
    ) which would help be execute some action in case there have been some failures etc.? Since I think this is (or will be) a very common design pattern - similarly as there is a convenience ext. function for
    List<Deferred<T>>.awaitAll()
    . Recently I was thinking it could be done in the similar fashion as the current
    .onFailure()
    and
    .onSuccess()
    except that the lambda would take
    List<Throwable>
    or
    List<T>
    as an argument (respectively). Currently what I need to do on such list, is: (1)
    filter { it.isFailure}
    , then (2) I need to check that it is not empty, and not until now (3) I can do something with it. With the above proposal the first 2 steps would be unnecessary and I would be able to define just the part which would execute only if there was at least 1 failed Result. Similarly it could work for successful Result values.
    g
    d
    i
    • 4
    • 18
  • k

    karelpeeters

    10/31/2018, 6:26 PM
    Iterable<Pair<K, V>>.toMutableMap()
    is "missing", that confused me for a second 😒imple_smile:
    i
    l
    • 3
    • 3
  • h

    hmole

    11/07/2018, 11:09 AM
    Any chance we can get nested destructive declarations in Kotlin?
    val (a,(b,c)) = 1 to (2 to 3))
    ?
    🤔 1
    w
    e
    g
    • 4
    • 5
  • l

    louiscad

    11/14/2018, 2:47 PM
    Hi! Is there a reason the stdlib doesn't have these 2 extension functions to delegate a property from another one?
    inline operator fun <R> KProperty0<R>.getValue(thisRef: Any?, property: KProperty<*>): R = get()
    inline operator fun <R> KMutableProperty0<R>.setValue(thisRef: Any?, property: KProperty<*>, value: R) {
        set(value)
    }
    Here's a link to an example snippet: https://pl.kotl.in/HyLn42KaQ
    i
    • 2
    • 3
  • h

    hho

    11/15/2018, 11:32 AM
    listOf(*yourArray)
    ?
    Nope, see @gildor s Response in the thread
    g
    • 2
    • 3
  • g

    guenther

    11/15/2018, 12:56 PM
    In the Stdlib the companion of
    Byte
    looks like this:
    public class Byte private constructor() : Number(), Comparable<Byte> {
        companion object {
            public const val MIN_VALUE: Byte = -128
            public const val MAX_VALUE: Byte = 127
    ...
    Double
    on the other hand looks like this:
    public class Double private constructor() : Number(), Comparable<Double> {
        companion object {
            public val MIN_VALUE: Double
            public val MAX_VALUE: Double
    ...
    Is there are a particular reason, why the properties in
    Double
    are not
    const
    ? This prevents me to use those properties in my own constants.
    🤔 3
    s
    c
    • 3
    • 5
  • d

    dave08

    11/15/2018, 5:38 PM
    Maybe there should be
    associateWithNotNull { }
    for when the value is resolved to be
    null
    , just like
    mapNotNull { }
    ?
    • 1
    • 2
  • g

    gabrielfv

    11/29/2018, 4:30 PM
    Is there a reason for there not being a `findIndexed()`/`firstOrNullIndexed()` method for the
    Iterable
    class, which takes a
    (T) -> Boolean
    predicate and returns
    IndexedValue<T>
    ?
    o
    i
    • 3
    • 3
  • g

    gabrielfv

    11/29/2018, 4:31 PM
    Also, is there any performance impact of using
    for (a in withIndex()) ...
    rather than
    var i = 0; for (a in iterable) { ...; a++ }
    ?
    g
    • 2
    • 4
  • m

    Mark

    11/30/2018, 7:23 AM
    What is the more concise way to write
    if (arg == null) null else myfun(arg)
    ? I can only think of
    arg?.let { myfun(it) } ?: null
    but this seems less readable to me.
    g
    v
    h
    • 4
    • 11
  • s

    spand

    12/06/2018, 12:49 PM
    Is there something similar to
    reduce
    that works for empty collections by returning
    null
    ? I can see that there are specializations of it (
    .minBy
    ,
    .minWith
    , ..) but a general version escapes me.
    e
    m
    • 3
    • 2
  • d

    Dias

    12/06/2018, 11:17 PM
    Is there a standard function that would split collection into buckets depending on some parameter?
    s
    p
    h
    • 4
    • 11
  • r

    rrader

    12/08/2018, 2:55 PM
    Why Kotlin does not have
    Either
    class? https://www.scala-lang.org/api/2.9.3/scala/Either.html
    m
    a
    r
    • 4
    • 7
  • m

    Marc Knaup

    12/11/2018, 8:18 AM
    I love this, what do you think? 🙂
    inline fun <R> Boolean.thenTake(action: () -> R) =
        if (this) action() else null
    
    val result = if (input) something() else null
    ->
    val result = input.thenTake { something() }
    g
    e
    +2
    • 5
    • 27
  • s

    stevecstian

    12/12/2018, 9:18 AM
    Why
    eachCount
    is not listed in https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-grouping/index.html#extension-functions now? Did I miss anything?
    👍 1
    i
    • 2
    • 3
  • c

    cbruegg

    12/13/2018, 7:18 PM
    It makes sense since they're not instances of the same class. And if I remember the contract of
    equals
    correctly, the class needs to be identical and not just be subclasses of the same type.
    ☝️ 1
    i
    • 2
    • 1
  • d

    Dias

    12/17/2018, 2:44 PM
    is there a way to get previous item while mapping through the sequence?
    m
    • 2
    • 2
  • s

    Shawn

    12/17/2018, 2:46 PM
    zipWithNext
    will group items together into pairs if that works for you
    d
    d
    p
    • 4
    • 12
  • r

    robin

    12/18/2018, 10:19 AM
    Does anyone know why the return type of
    Sequence<T>.partition
    is
    Pair<List<T>, List<T>>
    , and not
    Pair<Sequence<T>, Sequence<T>>
    ? It would be nice to keep the lazyness even through a partitioning operation.
    g
    • 2
    • 2
  • t

    thomasnield

    12/18/2018, 9:28 PM
    Just ran into a complex number problem by taking the cubed root of a negative number
    (-4.0).pow(1.0/3.0)
    , which returns
    NaN
    due to lack of support for imaginary numbers. However, Java has
    Math.cbrt()
    specifically for this purpose. Is this something Kotlin should explicitly support?
    d
    • 2
    • 1
  • d

    Dias

    12/19/2018, 5:00 PM
    Why is
    String.toInt()
    just an alias for
    parseInt()
    , but
    String.toIntOrNull()
    is custom implementation instead of trycatch implementation of parseInt()? Is it because throwing exceptions in java is heavy or something like that?
    g
    r
    • 3
    • 2
  • r

    rrader

    12/24/2018, 1:35 PM
    https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/jvm/runtime/kotlin/jvm/internal/Intrinsics.java#L138 Can you please replace
    IllegalArgumentException
    with another exception? that will store property name and will be possible to get that property name and not to parse the error string
    👍 1
    k
    g
    s
    • 4
    • 87
Powered by Linen
Title
r

rrader

12/24/2018, 1:35 PM
https://github.com/JetBrains/kotlin/blob/master/libraries/stdlib/jvm/runtime/kotlin/jvm/internal/Intrinsics.java#L138 Can you please replace
IllegalArgumentException
with another exception? that will store property name and will be possible to get that property name and not to parse the error string
👍 1
k

karelpeeters

12/24/2018, 1:39 PM
Why do you need to catch it?
r

rrader

12/24/2018, 1:50 PM
We build a Json library, and need to create a instance of class, and need to show what field failed
to not break the code, the new exception class can be a child of
IllegalArgumentException
k

karelpeeters

12/24/2018, 1:55 PM
Can't you look at the type of the arguments?
r

rrader

12/24/2018, 1:57 PM
These check are already done by Kotlin, so we want to reuse them
k

karelpeeters

12/24/2018, 3:19 PM
Hmm, `IllegalArgumentException`s aren't meant to be caught, even in Java. They should always be indicative of a programmer error.
g

gildor

12/25/2018, 2:19 AM
I agree with Karel, reuse asserts for this doesn't seem correct for me. Parsing shouldn't create instance or class. If you use reflections you can check nullability of constructor argument
r

rrader

12/26/2018, 7:54 AM
And how will be if Kotlin team will allow to disable this checks? We should rewrite our code? Why not just reuse this checks?
And why to limit library writers? Kotlin team just need to provide good tools, after is our decision to use or not
g

gildor

12/26/2018, 8:35 AM
And how will be if Kotlin team will allow to disable this checks
Yes, you right, this check already can be disabled using compiler flag
Why not just reuse this checks?
Because it not intended to be reused
And why to limit library writers
I don’t see any limitation.s You already has tools to solve this problem: kotlin-reflect and kotlin-metadata
r

rrader

12/26/2018, 9:43 AM
Well, as you said we also should check the compiler flags
And also should track if other ways will not apear to disable that checks
Because it not intended to be reused
why to not make to be reused, do you know some limitations?
g

gildor

12/26/2018, 9:47 AM
Well, as you said we also should check the compiler flags
No! You shouldn’t if you just check it yourself
r

rrader

12/26/2018, 9:48 AM
Hm, how can I check if I not check the flags?
g

gildor

12/26/2018, 9:50 AM
As I said before, you shouldn’t rely on runtime asserts to validate serialized data. Instead, you should rely on semantics of original code. To do that you check constructor arguments nullability using kotlin-reflect (for runtime) or metadata information (for compile-time) So yes, you should check nullability yourself, do not expect that runtime will throw exception
r

rrader

12/26/2018, 9:51 AM
Ok, what should I check with kotlin-reflect?
g

gildor

12/26/2018, 9:52 AM
This is what all Kotlin specific serialisers do like kotlinx.serialization, moshi-kotlin, #klaxon etc
r

rrader

12/26/2018, 10:00 AM
ok, but what should I check with kotlin-reflect?
g

gildor

12/26/2018, 10:03 AM
that argument is nullable or not
so if it’s nullable it’s fine to pass null there, if not, but deserialized value is null you should throw own error or handle it in some other way
r

rrader

12/26/2018, 10:05 AM
this is not correct with flags
the flags will not remove nullability from parameters, they just remove intrisics
g

gildor

12/26/2018, 10:06 AM
I don’t understand what you mean
yes, of course
but why would you check for intrinsics behaviour?
need to create a instance of class, and need to show what field failed
this is your original task
r

rrader

12/26/2018, 10:07 AM
because validation is done by other tool not by kotlin
g

gildor

12/26/2018, 10:07 AM
to solve it, you validate data before actual instance creation
r

rrader

12/26/2018, 10:08 AM
so, double work
g

gildor

12/26/2018, 10:08 AM
Maybe you could give more context, because it’s now not clear for me what you want to achieve. What is your case, when instance creation may be failed because of nullability?
If validation is done already, why would you handle intrinsic errors which signal only about incorrect state
r

rrader

12/26/2018, 10:10 AM
I want what nullability validation to be done by other tool, not kotlin, because kotlin fail on first parameter, and I need to collect all possible errors, I need this when receive json from client
the validation by tool is done only after object creation
g

gildor

12/26/2018, 10:10 AM
In this case you don’t validate data, you validate that mapping of data to kotlin code is valid, so not sure how 3rd party tool can do that
r

rrader

12/26/2018, 10:10 AM
this is why I need to disable kotlin checks
g

gildor

12/26/2018, 10:11 AM
I want what nullability validation to be done by other tool, not kotlin, because kotlin fail on first para
how 3rd party tool can check nullability of Kotlin types?
r

rrader

12/26/2018, 10:13 AM
kotlin adds
@NotNull
to that parameters, so after object creation the tool can check properties that has this annotation if they are null
g

gildor

12/26/2018, 10:14 AM
What kind tool it is?
r

rrader

12/26/2018, 10:14 AM
Spring +
@Valid
so if a parameter in Spring has
@Valid
it will validate the object before passing to method
g

gildor

12/26/2018, 10:15 AM
okay, probably would be better to start from this, that you use Sprint and JSR-303
r

rrader

12/26/2018, 10:16 AM
well, maybe
g

gildor

12/26/2018, 10:16 AM
Did you see this? https://stackoverflow.com/questions/35847763/kotlin-data-class-bean-validation-jsr-303
r

rrader

12/26/2018, 10:17 AM
not this, but I already use the annotation, the only issue is with
null
because kotlin fail on first null
g

gildor

12/26/2018, 10:18 AM
I don’t think that you can solve it now, only marking properties as nullable, same way as it work in Java
r

rrader

12/26/2018, 10:18 AM
I can't do all other checks, because I can not create the object
g

gildor

12/26/2018, 10:19 AM
Another option tot somehow integrate Kotlin support to spring validation
I think only working solution is mark everything as nullable
r

rrader

12/26/2018, 10:19 AM
no
I already made it
g

gildor

12/26/2018, 10:20 AM
and what did you do?
r

rrader

12/26/2018, 10:20 AM
just need to thor anothr exception
and thats it
I have all my requests/json in separate module, disabled intrisics only for this module, and validation is done by Spring, but in kotlin jackson module that is using by Spring they also check paramers before object creation, so if in that module check will be reused everything will work
so to fix this in jackson kotlin module I just need to throw a new exception
g

gildor

12/26/2018, 10:23 AM
Looks like really dirty hack rather than solution
But I see your pain. JSR-303 is too java-specific
r

rrader

12/26/2018, 10:25 AM
maybe it's a hack, but everything works as expected
g

gildor

12/26/2018, 10:25 AM
we probably need some proper solution for this on Kotlin
like compiler plugin that validates before object creation or some Spring integration that doesn’t try to construct invalid object, but checks data before object creation
r

rrader

12/26/2018, 10:26 AM
I have an idea now, maybe to add as metadata to each parametr if intrisics was generated for it, so in library we can check just that info
no matter what disabled the intrisics, we just check that info
the issue with plugin will be that validation can be custom, and it only works after object creation, so it will not be a working solution
g

gildor

12/26/2018, 10:29 AM
I still think that solution with intrinsic disabling is bad. Because you actually need intrinsics, not valid class shouldn’t be created, at least in theory
on can be custom, and it only works after object creation,
why? Because validation checks other fields?
r

rrader

12/26/2018, 10:31 AM
also, it can has some logic, or even read from database
this is how work Spring + JSR-303
it create object and after that do validation
another point is, that object is created by jackson library, and in jackson library do not want to add anything about validation
I will be happy to not disable intrisics, but I need a working solution 🙂
g

gildor

12/26/2018, 10:37 AM
Yes, I understand
Annotation to disable intrinsics also may be implemented as compiler plugin, but it’s long term solution
r

rrader

12/26/2018, 11:18 AM
do you mean https://youtrack.jetbrains.com/issue/KT-23335 ?
s

sandwwraith

12/26/2018, 2:42 PM
This would be eventually replaced with `KNPE`: https://youtrack.jetbrains.com/issue/KT-22275
r

rrader

12/26/2018, 2:45 PM
Oh, thanks also in #klaxon also recomand to do validation after object creation https://kotlinlang.slack.com/conversation/C90AVCDQU/p1545835141006600
s

sandwwraith

12/26/2018, 2:46 PM
Well, it makes some sense: validation happens after creation, and if object can not be created, there's nothing to validate
g

gildor

12/26/2018, 3:28 PM
I don't see that Klaxon recommended to do validation after object creation, just that Klaxon doesn't provide any facilities for custom validation. Also, Klaxon checks for nullability of arguments and will not allow create an object if nullability doesn't match to argument even without intrinsic assert I believe that 2 steps of validation is just fine. Checking for null is not something different from checking that property type is compatible, that you do not try to deserialize array to int or other basic type-system check. Validator of any (de)serializer does basic checks in any case and even sometimes provide some facilities for fallback, like use default value (predefined or default for particular type, like 0 or empty string) The only reason why nullability is part of jsr-303 is that Java doesn't have nullability on type system (same way as Kotlin or Java don't have number range check) The same way Jackson in Spring will throw exception before class instance creation in case of incompatible types.
I understand that it probably not what Spring provides out of the box, but I think it's right approach. Also really curious, do you use Jackson-module-kotlin? Because I thought that it should provide nullability check before object creation and do not create invalid objects
r

rrader

12/26/2018, 3:45 PM
Yes I use that module, and yes it checks before creation
And I want to modify that behavior
Well, user of application will not be happy to see 2 times validation errors
he expect to see at once all the validation errors
g

gildor

12/26/2018, 4:02 PM
But user will see only 1 validation error, depending on level of error (deserializer or validator). Also it's possible to avoid nullability for most cases, especially with power of Jackson: use default values for primitives (I believe this is already default behavior), empty string and empty collections and default values for your own classes Of course it depends on use case, but probably better just solve nullability problem on serializer level rather than on high level validator
r

rrader

12/26/2018, 8:59 PM
But user will see only 1 validation error
this is the problem, user want to see all errors at once
use default values for primitives
hm, usually you do not have default at all
View count: 2