https://kotlinlang.org logo
#announcements
Title
# announcements
g

Gyuhyeon

12/31/2019, 8:53 AM
I'm confused with a somewhat basic concept -
Copy code
data class Foo(
    val bar: Long? = null
)
consider this simple class. Using mybatis, a
select
query from a database table is mapped into this class. I know that mybatis by default uses default noarg constructor, then uses setters to set the value. However, decompiling the above kotlin class reveals that bar is indeed
private final Long
. When default constructor is called, it seems to me that kotlin will use its synthetic method to automatically set
bar
as null. This would mean that bar cannot be set even with reflection magic. Does anyone have any idea how
val
fields could possibly be mapped correctly from mybatis?
j

Jérôme Gully

12/31/2019, 8:57 AM
Are you confused by the
data
keyword ?
g

Gyuhyeon

12/31/2019, 8:57 AM
@Jérôme Gully sorry, pressing return even in a codeblock submitted it for some reason. it has been edited.
😁 1
m

Marc Knaup

12/31/2019, 9:01 AM
val
fields are immutable by definition. If you want it to be set after the class has been instantiated you must use
var
. I’m surprised that
Foo
even has a no-arg constructor internally. It shouldn’t
🤔 Ah, it has one if all parameters have default values. Interesting.
j

Jérôme Gully

12/31/2019, 9:01 AM
You can change to
var bar
. edit:Oups to late
g

Gyuhyeon

12/31/2019, 9:05 AM
To clarify: this works with mybatis. I am just confused why, because by definition it shouldn't work. The reason this creates noarg constructor is because of all the default value settings in the primary constructor. But upon debugging a bit more, it seems like mybatis uses the constructor with argument instead when using kotlin. must be mybatis' kotlin support changes i guess
So, it seems like while mybatis with java class works with noargs constructor and then uses setters, when used with kotlin class it smartly uses argument constructors. weird.
P.S https://stackoverflow.com/questions/47562935/mybatis-with-immutable-data-classes-in-kotlin I had googled this topic, and found a single SO question with 0 answers, heh
m

Marc Knaup

12/31/2019, 9:06 AM
How would it set final fields in Java then? And why wouldn’t it use the constructors in Java? The framework can’t really know what constructor parameter is what property 🤔
Maybe it’s possible to set final fields with reflection on the JVM.
Yup, it uses tons of reflection, including making private final fields accessible and settable.