What happens if my library uses a new function in ...
# getting-started
j
What happens if my library uses a new function in the stdlib but the project importing my library is on an older version of the stdlib (which doesn't contain this new function)?
Another way to put the question: when publishing a library built with Kotlin 1.9.10, can a project built with Kotlin 1.8.10 depend on this library? If so, are there any pitfalls?
In case you were wondering, I tried the following setup: • The library is using KT 1.9.10, it exposes a
test
function which calls the new `hexToLong` method internally • I've got a project using KT 1.8.21, which depends on my library • When running, the project calls the
test
function from the library • Everything works fine
So I suppose a Kotlin project always uses the latest version of the standard library?
h
It depends on the target. On JVM it will fail with a runtime error. Before 1.9.0, the Kotlin Native compiler fails, now it will fail at runtime too. If you want to support older Kotlin versions, set the api level. Except inline functions obviously.
But if your library exposes the stdlib as api dependency, it might be possible your consumer will use a higher stdlib than defined in Gradle.
j
the library might return some things from the stdlib yes, like collections for example, or even open-ended ranges I'm not sure what version of the stdlib a project will use if it depends on my lib
h
Ideally, just set the api version and you are safe. Then you can’t use newer APIs, this will result into a compiler error.
j
I can, but I do not understand why I should do this? Why did my project worked despite using an older Kotlin version that the library one? And why the official Kotlin libraries do not use
apiVersion
too? (for example, kotlinx.datetime)
h
I can’t say why your project did work, a reproducer or public link would help. kotlinx datetime and other libs explicitly state the used Kotlin version. Datetime is experimental, so the api can change (which will do in 0.4.1 with the new 1.9.0 CompareableTimeMarks) and other libs like coroutines only increase the stdlib for each minor release.
j
I've been searching a bit, seems like you're right, I will set this compiler option for safety 🙂
Thank you!
j
If your library is published with 1.9.0-stdlib as a dependency and a consumer app, which uses 1.8.0-stdlib, declares your library as a dependency, Gradle should pull in the 1.9.0-stdlib transient dependency version because it's the higher version number.
🙏 1
At least on JVM, that is.
h
By default yes, but you could strictly depend on 1.8
👍🏼 1