Suggest new operation combining 'when' & 'with'


#1

few days ago I asked a question on stackoverflow.

and after few days I wonder if the below code is possible.

private fun getTouchX(): Int = whenWith(arguments) {
        containsKey(KEY_DOWN_X) -> getInt(KEY_DOWN_X)
        else -> centerX()
    }

‘containsKey’ and ‘getInt’ is arguments’s method.
and ‘centerX’ is Class method

is there a way to do this?
if not I suggest a advenced when and I want to call this whenWith.


#2

I think this is related to this topic, but instead of passing the value through, use the value as receiver, if I’m right.

Ps. I think the way i would write your code is:

 arguments?.takeIf{ it.containsKey(KEY_DOWN_X) }
   ?.getInt(KEY_DOWN_X)
   ?: centerX()

Or even better, create an extensionFunction like
getOrElse

inline fun <reified T> Bundle.getOrElse(
    key: String, 
    compute: () -> T?
): T = (this[key] as? T)?: compute()

Note, the compute will also be called if T is the incorrect type.

The other solution is like you original did

inline fun <reified T> Bundle.getOrElse(
    key: String, 
    compute: () -> T?
): T = takeIf{it.containsKey(key)}
   ?.let{this[key] as T)} 
   ?: compute()

And then you throw an error by the incorrect type