[ScopedValue] best way to conditionally bind a value ?

Benoit LEFEVRE -CAMPUS- benoit.lefevre at decathlon.com
Wed Jul 30 18:16:58 UTC 2025


Hello

After using the ScopedValue for a few days, I'm wondering if there is a
better way to conditionally bind a value than doing the following :


public static final ScopedValue< Locale > ACCEPT_LANGUAGE =
ScopedValue.newInstance();
public static final ScopedValue< String > USER_ID =
ScopedValue.newInstance();

final Locale acceptLanguage = getAcceptLanguageFromHeader( httpRequest );


if( acceptLanguage == null ) {
    ScopedValue
        .where( USER_ID, uid )
        .call( MyClass::myStaticCallableMethod );
} else {
    ScopedValue
        .where( USER_ID, uid )
        .where( ACCEPT_LANGUAGE, acceptLanguage )
        .call( MyClass::myStaticCallableMethod );
}


The point for me of doing so, instead of simply setting a null
acceptLanguage, is to have a more readable code afterward :


private String myStaticCallableMethod() {
    final Local localToUse = ACCEPT_LANGUAGE.orElse( A_DEFAULT_LOCAL );


    ...
}


What is your advise about it ?


Best regards

-- 
Benoit Lefèvre
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/loom-dev/attachments/20250730/f4846472/attachment.htm>


More information about the loom-dev mailing list