Skip to content

Add whatIfMap explicitly for Modifier without need of default value #25

@amirkazemzade

Description

@amirkazemzade

Since for Modifiers we should use a WhatIfMap pattern, and the WhatIfMap needs a default value or a 'what-if-not' callback to work, I tried implementing it without the need for a default value (by returning the current value for 'what-if-not' by default).

The Problem (Root Cause):

The Modifier's companion object causes a type inference issue. The compiler treats the generic type T as if it is Modifier.Companion, and consequently throws an error when trying to return the Modifier interface.

This behavior is part of the core framework implementation and cannot be changed by us. However, Modifier usage in Compose is so widespread that this technical issue severely limits the use of clean WhatIfMap patterns.

Proposed Solution:

We request a feature to add an explicit, dedicated method (e.g., an extension function) solely for the Modifier interface, similar to what have done with the Boolean types. This would allow us to bypass the compiler's type inference issue with the companion object, enabling developers to use clearer, nullable-friendly conditional modifier logic.

Proposed Implementation:

I've already implemented this feature for my own usage, and I'm happy to submit a pull request if you agree to include it in the main library:

@JvmSynthetic
inline fun Modifier.whatIfMap(
    given: Boolean?,
    whatIf: (Modifier) -> Modifier,
): Modifier {
    contract {
        callsInPlace(whatIf, InvocationKind.AT_MOST_ONCE)
    }
    if (given == true) {
        return whatIf(this)
    }
    return this
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions