Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do method references in RxJava work?

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();
like image 519
Grzegorz D. Avatar asked Nov 10 '16 18:11

Grzegorz D.


People also ask

How does method reference work?

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.

How does Java method reference work?

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.

HOW ARE method references useful?

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.

What is static method reference in Java?

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 .


1 Answers

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.

like image 69
Michał Šrajer Avatar answered Sep 18 '22 19:09

Michał Šrajer