https://kotlinlang.org logo
Title
b

Big Chungus

08/03/2019, 4:34 PM
Is there any way to get kotlin property's default value?
d

Dominaezzz

08/03/2019, 4:35 PM
I'm not sure if Kotlin does defaults.
b

Big Chungus

08/03/2019, 4:36 PM
i mean
data class Test(val x:String="I'm default")
How do I get "I'm default" from KProperty1<Test,String> ?
d

Dominaezzz

08/03/2019, 4:38 PM
Ah, this is reflection territory. I'm not sure how but you can get it via reflection.
Can I ask why you need this?
Ah!
x
property does not have a default value!
But
x
constructor parameter has a default value.
b

Big Chungus

08/03/2019, 4:40 PM
I need it in JS to handle undefined states...
Ah, got it
That helps
r

Robert Jaros

08/03/2019, 5:13 PM
Reflection is JS is not possible generally
k

karelpeeters

08/03/2019, 8:12 PM
The problem is that default values are actually full pieces of code, for example:
fun foo(x: List<Int> = listOf(1, 2, 3)) {}
You can't really get a default value from that, it's an expression that needs to be evaluated every time.
m

Marko Mitic

08/03/2019, 8:31 PM
Even worse, you can have this:
fun foo(x: Int, y: Int = x+1)
k

karelpeeters

08/03/2019, 8:54 PM
That's good to know actually, and yes that's a lot worse!