I have an issue with default params and backward c...
# random
y
I have an issue with default params and backward compatibility in a kotlin library: my use case is: I have a library that is used by me and by other libraries I use so if I update my version then the code in the 3rd party library is changed but the calls to functions/constructors remain as they where. For example: the lib has a class
A
Copy code
data class A(val x:String)
then we update the lib so that
A
has another val
Copy code
data class A(val x: String, val y: String = "")
I used default parameters so everything should be fine, but it not. the third party library will continue to call
A("something")
to a constructor that doesn’t exist and I am getting a
Copy code
java.lang.NoSuchMethodError: A.<init>(Ljava/lang/String;ILkotlin/jvm/internal/DefaultConstructorMarker;)V
@JvmOverloads
doesn’t help. Any solutions for this?
m
Such a change is, most probably, source compatible but not binary compatible. So you have to recompile all your code that depends on this library.
y
so what other pattern can be used to avoid a recompile of all libraries that depend on that code?
m
Here, adding a secondary ctor with 1 parameter should help. And maybe if you have at least one optional parameter, then adding next will be compatible. Maybe there are also some other annotations, like JvmOverloads (which looks like it should have helped here anyway).
y
wouldn’t adding another param later would force me to create a third constructor and so on?
e
you cannot easily extend a data class and keep binary compatibility: not only the constructor, but also the generated
copy
method changes
https://jakewharton.com/public-api-challenges-in-kotlin/
The only real way to avoid these binary-incompatibilities for public API is to avoid the
data
modifier from the start and implement
equals
,
hashCode
, and
toString
yourself.
y
what I am thinking that can solve this is not using a data class and creating a builder pattern I read that article, I would love to have a auto generated builder boilerplate
107 Views