Published on

Using Kotlin's Deprecated Annotation with ReplaceWith

Authors

I was working through a code base today and saw we had an enum that was being used in many many places but had been replaced by another more correct enum. For simplicity pretend this enum is called DirectionType. We want to deprecate this and indicate that it should be replaced with another enum called CardinalType. In Java you would use the @Deprecated annotation and you would then have to create a Java doc above this to indicate additional information.

I personally despise comments - they essentially pollute your code and will rot over time. 99.99% of the time you should be able to replace your comment with well named variables, methods and classes. </rant>

Anyway in Kotlin there is also a @Deprecated annotation but this one is far more powerful. You can provide a message for the deprecation indicating the reason for the deprecation. You can give a deprecation level which is either ERROR, HIDDEN or WARN and you can specify what to replace it with: replaceWith. The ERROR deprecation level will prevent your code from compiling if it uses this deprecated code. WARN will give you IDE and compile time warnings. HIDDEN is meant to stop your IDE from suggesting this code but I found it behaves the same ass ERROR.

Where this annotation comes really in handy is with the replaceWith. You specify as a first parameter to this the class/enum you want to replace the given code with. You then specify as the second parameter the fully qualified class name that will be used to import. Now in your IDE if you encounter one of these code usages the IDE will strike through this code (as with Java), give you a message for why its deprecated and have a code assist suggestion to replace this with the class you indicated 😎

package your.company.enumeration

@Deprecated(
    message ="This is not applicable to YourProduct",
    replaceWith = ReplaceWith("CardinalType","your.company.constants.CardinalType"),
    level = DeprecationLevel.WARNING
)
enum class DirectionType {
    LEFT, RIGHT, UP, DOWN
}

To read up more on how this works check out the official documentation.