In Kotlin, we can use @Deprecated Annotation to mark a class, function, property, variable or parameter as deprecated. What makes this Annotation interesting is not only the possibility to deprecate but also provide replacement with all the necessary imports. This comes handy for clients to upgrade the source code without digging into documentation. Apart from this we can also control the level of depreciation. Let see it in action.

The minimal thing we need to mark a function as deprecated is to Annotate the function and provide the deprecation message. Thanks to java interoperability we can use this Annotation within existing java code base.

@Deprecated(message = "we are going to replace with StringUtils.isEmpty) public static boolean isEmpty(String input) { return input.equals(""); }

It will be nice if we can have the possibility to provide the replacement code as part of IDE suggestion that can help a client to upgrade their code base. @ReplaceWith aims to achieve exactly this. It takes 2 arguments :

expression – method call to replace with. imports – necessary import to make an expression compile.

E.g.

@Deprecated(message = "we are going to replace with StringUtils.isEmpty", replaceWith = @ReplaceWith( expression = "StringUtils.isEmpty(input)", imports = {"org.apache.commons.lang3.StringUtils"}) ) public static boolean isEmpty(String input) { return input.equals(""); }

Depending on the use case, we can also tweak the deprecation level for an immediate upgrade. Supported levels are:

Warning – will result in compilation warning. It is also the default level. Error – will result in compilation error Hidden – deprecated method will be hidden in the code base (non-existing for the caller), but will be present at bytecode level. This is useful in scenarios where we want to pretend the method doesn’t exist at the source code level but want to keep it at bytecode level (due to compatibility reason).

E.g.

@Deprecated(level = DeprecationLevel.ERROR, message = "we are going to replace with StringUtils", replaceWith = @ReplaceWith( expression = "StringUtils.isEmpty(input)", imports = {"org.apache.commons.lang3.StringUtils"}) ) public static boolean isEmpty(String input) { return input.equals(""); }

E.g.

@Deprecated(level = DeprecationLevel.HIDDEN, message = "we are going to replace with StringUtils", replaceWith = @ReplaceWith( expression = "StringUtils.isEmpty(input)", imports = {"org.apache.commons.lang3.StringUtils"}) ) public static boolean isEmpty(String input) { return input.equals(""); }