Setters optimize

Hello all

How to implement custom operator for check value before set. Example

if (mView.isVisible != true)
     mView.isVisible = true

to
mView.isVisible ?= true

and maybe more complex example

if (mView.isVisible != true)
   if (isUIThread)
     mView.isVisible = true
   else
     mView.post { mView.isVisible = true }

to
mView.isVisible ?= true

Have ideas?

Please note - the code below has potential concurrent issues:

if (mView.isVisible != true)
   if (isUIThread)
     mView.isVisible = true
   else
     mView.post { mView.isVisible = true }

However if you want to achieve this behaviour, I can advice the following:

fun <TView: View> setVisible(newValue: Boolean) {
if (isVisible != newValue)
   if (isUIThread)
    isVisible = newValue
   else
    post { isVisible = newValue }
} 

Next if you have another view, which can have interface (for example - interface Countable { var count: Int; }, you can do something like this:

fun <TView> setVisible(newCount: Int)
 where TView: View, Countable {
if (count != newValue)
   if (isUIThread)
    count = newValue
   else
    post { count = newValue } // <-- View inheritance is needed for post method
} 
1 Like

Nope
idea for universal like this. You example is to simple)))

fun <T>operator T.`?=` (vauel: T){
    if (leftSide.val != value)
        leftSide.set(value)
}

In order to be added to the language, an operator must be either:

  • very common among the other languages,
  • or intuitive for almost everyone (regardless of experience in the other languages),
  • or able to reduce very large amount of boilerplate in the average code.

The proposed operator does not meet any of these criteria, IMO

5 Likes

The ?= operator can become misleading very soon.

In observable methods, each assignment creates a reative. Therefore, the entire android code consists of verification and set, instead of just a set.