I'm confused with a somewhat basic concept - ```da...
# announcements
g
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
Are you confused by the
data
keyword ?
g
@J茅r么me Gully sorry, pressing return even in a codeblock submitted it for some reason. it has been edited.
馃榿 1
m
val
fields are immutable by definition. If you want it to be set after the class has been instantiated you must use
var
. I鈥檓 surprised that
Foo
even has a no-arg constructor internally. It shouldn鈥檛
馃 Ah, it has one if all parameters have default values. Interesting.
j
You can change to
var bar
. edit:Oups to late
g
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
How would it set final fields in Java then? And why wouldn鈥檛 it use the constructors in Java? The framework can鈥檛 really know what constructor parameter is what property 馃
Maybe it鈥檚 possible to set final fields with reflection on the JVM.
Yup, it uses tons of reflection, including making private final fields accessible and settable.