rusttraits

Kotlin scope functions in Rust?


Studying Rust and Kotlin at the moment, I wonder whether something as neat as Kotlin's Scope functions (let, apply, run, etc.) could be / are implemented in Rust?


Solution

  • It looks like Kotlin's scope functions don't have an equivalent in the Rust standard library but the functionality is available via extension methods from the popular tap crate.

    The Tap methods run a closure given the value and return the original value:

    use tap::Tap;
    
    let b = make_a()
        .tap(|a| log!("The produced value was: {a}"))
        .into_b();
    

    The Pipe methods run a closure given the value and return a new value:

    use tap::Pipe;
    
    let c = make_a()
        .pipe(|a| process_a_to_b(a))
        .pipe(|b| process_b_to_c(b));
    

    There is no Rust distinction between between Kotlin scope functions that use it vs this since Rust closures only have named parameters (and captured variables), there are no implicit parameter names or implicit-this.