How do method references in RxJava work?
Asked Answered
P

1

6

Can someone explain me, how come both of the lambdas can be replaced with method references here?

In RxJava, map() takes a parameter of type Func1<T, R>, whose comment states that it "Represents a function with one argument". Thus I completely understand why valueOf(Object) works here. But trim() takes no arguments at all.

So how does this work exactly?

Observable.just("")
    .map(s -> String.valueOf(s))  //lambdas
    .map(s -> s.trim())           //

    .map(String::valueOf)         //method references
    .map(String::trim)            //
    .subscribe();
Presently answered 10/11, 2016 at 18:48 Comment(1)
The way method references work is that for instance methods like trim, Type::instanceMethod is equivalent to (Type t) -> t.instanceMethod(). (More generally, Type::instanceMethod is (Type t, extraArgs) -> t.instanceMethod(extraArgs).)Parthia
C
3

I didn't play with RX in java, but please note, that String::valueOf is a static (aka unbound) function, while String::trim is a non-static (aka bound) function that have indirect this argument. So, in fact, both function takes single argument. In Java it's not that visible as it is in Python for example.

Capriola answered 10/11, 2016 at 18:55 Comment(4)
Note that you can actually explicitly declare the this argument in Java; it just isn't required. public void foo(Foo this) {} is equivalent to public void foo(){}.Phemia
@Phemia I like this. Wasn't aware. Since what java version? Do you know?Centavo
I'm pretty sure it was added in Java 8.Phemia
The Foo this is called a "receiver parameter" and is specified in JLS, §8.4.1. You can do the same thing with inner class constructors, e.g. an outer class Foo with inner class Bar whose constructor can be written as Bar(Foo Foo.this).Marseilles

© 2022 - 2024 — McMap. All rights reserved.