Created
November 13, 2019 16:58
-
-
Save AppLoidx/99ac16d253e6b8f73489c4ff6711f577 to your computer and use it in GitHub Desktop.
Void-compatible and value-compatible lambdas
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main; | |
import java.util.function.Consumer; | |
import java.util.function.Predicate; | |
/** | |
* @author Arthur Kupriyanov | |
*/ | |
public class Something { | |
void run (Consumer<String> arg){}; | |
void run (Predicate<String> arg){}; | |
void func() { | |
run(str -> !!str.isEmpty()); | |
run(str -> str.isEmpty()); // Ambiguous method call | |
run(str -> { return str.isEmpty(); }); | |
run((Consumer<String>) str -> str.isEmpty()); | |
run((Predicate<String>) str -> str.isEmpty()); | |
run(String::isEmpty); | |
} | |
void weCantRunThisCode() { | |
boolean x = false; | |
!!x; // Not A statement | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/AppLoidx/99ac16d253e6b8f73489c4ff6711f577#file-something-java-L18
На строке с
run(str -> str.isEmpty());
компилятор не может определить является ли лямбда функция или void, или valueable. Например, при использованииConsumer
(которая void) иPredicate
(возвращает boolean)Компилятор в этом случае, не может гарантировать, что лямбда функция адресована к Consumer или к Predicate.
Поэтому, если использовать кастинга, то все скомпилируется. Также альтернативным решением будет явно указать
return
.Выражение
!!str.isEmpty
не может быть void-compatible т.к. выражение!!
в коде работать не будет, что приведено в https://gist.github.com/AppLoidx/99ac16d253e6b8f73489c4ff6711f577#file-something-java-L27