I’ve run into this problem a few times myself, and I haven’t found any pretty or kotlinish solution, yet.
You can either enforce the call of the
bar() in the contract of your library, but it is only a written contract, there is no compile time validation on using it.
Also you may check the variable in all your public functions, but that would pollute your code badly and it is error prone (if you left out your check in any of your functions).
So this is a feature one would really desire and it’s easy to show use cases for it. If a vote for library initializer would turn up, I vote for it. It would make life easier.
However, this mechanism is oppose how the java class loading works. The classloader would have to scan the whole classpath looking for init blocks and that’s resource consuming. That’s why it is not done and I think it won’t be done in the close future. That’s why all frameworks (like Spring) needs an entry point to be called implicitly.
When I have to do this kind of initialization, I use
reflections library (https://github.com/ronmamo/reflections, at last it works on Java8+) and use annotations or collect all implementations of an interface in the classpath. But even then I need an entry point to start the scan. This is not perfect, one could miss the call of the entry point, but it works and is the only way at the moment.