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();
The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.
Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.
The biggest benefit of the method reference or constructor reference is that they make the code even shorter by eliminating lambda expression, which makes the code more readable.
A static method reference refers to a static method in a specific class. Its syntax is className::staticMethodName , where className identifies the class and staticMethodName identifies the static method. An example is Integer::bitCount .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With