Scala conditional compilation

前端 未结 2 909
走了就别回头了
走了就别回头了 2021-01-28 11:12

I\'m writing a Scala program and I want it to work with two version of a big library.

This big library\'s version 2 changes the API very slightly (only

2条回答
  •  天涯浪人
    2021-01-28 11:35

    I see some options but none if them is "conditional compilation"

    • you can create 2 modules in your build - they would have a shared source directory and each of them you have a source directory for code specific to it. Then you would publish 2 versions of your whole library
    • create 3 modules - one with your library and an abstract class/trait that it would talk to/through and 2 other with version-specific implementation of the trait

    The problem is - what if you build the code against v1 and user provided v2? Or the opposite? You emitted the bytecode but JVM expects something else and it all crashes.

    Virtually every time you have such compatibility breaking changes, library either refuses to update or fork. Not because you wouldn't be able to generate 2 versions - you would. Problem is in the downstream - how would your users deal with this situation. If you are writing an application you can commit to one of these. If you are writing library and you don't want to lock users to your choices... you have to publish separate version for each choice.

    Theoretically you could create one project, with 2 modules, which share the same code and use different branches like #ifdef macros in C++ using Scala macros or Scalameta - but that is a disaster if you want to use IDE or publish sourcecode that your users can use in IDE. No source to look at. No way to jump to the definition's source. Disassembled byte code at best.

    So the solution that you simply have separate source directories for mismatching versions is much easier to read, write and maintain in a long run.

提交回复
热议问题