Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin @Deprecated ReplaceWith change function to variable assignment

Tags:

kotlin

I have the following function extension that I want to Deprecate

fun <T : View> T.setVisible(visible: Boolean) {
    visibility = if (visible) View.VISIBLE else View.GONE
}

Deprecated Usage:

myTextView.setVisible(true)

New Usage:

myTextView.isVisible = true

I'm trying write a @Deprecated ReplaceWith expression that will auto fix this deprecation. I tried the following, but it does not seem to work:

@Deprecated("Use Android KTX isVisible", replaceWith = ReplaceWith("isVisible = visible", "androidx.core.view.isVisible"))
fun <T : View> T.setVisible(visible: Boolean) {
    visibility = if (visible) View.VISIBLE else View.GONE
}

When I Alt+ENTER on the 'myTextView.setVisible(true)' and select 'Replace with isVisible = visible' from the popup, it just deletes my deprecated code

Is there an ReplaceWith expression that I can use to auto fix my code (changing a function call to an assignment)?

like image 348
Jeff Campbell Avatar asked Oct 27 '18 18:10

Jeff Campbell


1 Answers

Meanwhile here are some workarounds until the related bugs are fixed, all with there own specific drawbacks:

  1. replace with a useless cast:

    ReplaceWith("(this as T).isVisible = visible")
    

    which will transform your code to:

    (myTextView as View).isVisible = true
    

    An IDE may warn you that this cast is not needed, which you could fix in a second step

  2. using something like also

    ReplaceWith("also { it.isVisible = visible }")
    

    which transforms your code to:

    myTextView.also { it.isVisible = true }
    

    This code will probably not cause any warnings in your IDE, however it is clearly longer then needed

  3. similar as to before, but using apply:

    ReplaceWith("apply { [email protected] = visible }")
    // leading to:
    myTextView.apply { isVisible = true }
    

These workarounds are only really helpful, if you have no other way to easily change the callers code and want to give your callers some help to replace that deprecated code which doesn't instantly delete the most important information ;-) If you have access to the callers code, then you are probably better off just replacing it ~manually ;-)

like image 172
Roland Avatar answered Sep 28 '22 11:09

Roland