我正在编写程序并遇到这种错误:
类型Maybe的方法orElse(Integer)不适用于参数(字符串)
我得到的另一个错误是:无法从Object转换为String
msg = Maybe.of(txt)
.filter(t -> t.length() > 0)
.orElse("Txt is null or empty");
此外,我也不完全确定方法orElse()和filter()是否正常工作,但是由于出现此错误,我无法前进。谢谢您的帮助。
这是我的主语
package Maybe;
public class Main {
public static void test() {
Integer num = null;
// orElse() METHOD
// INSTEAD OF
String snum = null;
if (num != null) snum = "Value is: " + num;
if (snum != null) System.out.println(snum);
else System.out.println("Value unavailable");
// //ONE CAN WRITE
// String res = Maybe.of(num).map(n -> "Value is: "+n)
// .orElse("Value unavailable");
// System.out.println(res);
//filter(...) METHOD
String txt = "Dog";
String msg = "";
//INSTEAD OF
if (txt != null && txt.length() > 0) {
msg = txt;
} else {
msg = "Txt is null or empty";
}
//ONE CAN WRITE
// msg = Maybe.of(txt)
// .filter(t -> t.length() > 0)
// .orElse("Txt is null or empty");
// System.out.println(msg);
}
public static void main(String[] args) {
test();
}
}
还有我的Maybe课:
package Maybe;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
public class Maybe<T> {
T cont;
public Maybe(T val) {
this.cont = val;
}
public Maybe() {
}
public static <T> Maybe <T> of(T val) {
Maybe <T> m = new Maybe<T>(val);
return m;
}
public void ifPresent(Consumer<T> cons) {
if(isPresent()) {
cons.accept(get());
}
}
public <R> Maybe <T> map(Function<T, R> func) {
Maybe<T> mb = new Maybe();
if(isPresent()) {
mb = new Maybe(func.apply(get()));
}
return mb;
}
public T get(){
if(isPresent()) {
return this.cont;
} else {
NoSuchElementException exc = new NoSuchElementException("maybe is empty");
throw exc;
}
}
public boolean isPresent() {
if(this.cont != null) {
return true;
} else {
return false;
}
}
public T orElse(T defVal) {
if(isPresent()) {
return get();
}
return defVal;
}
public Maybe filter(Predicate pred) {
if(pred.test(pred) || !isPresent()) {
return this;
} else {
Maybe mb = new Maybe();
return mb;
}
}
public String toString() {
if(isPresent()) {
return "Maybe has value " + cont;
}else {
return "Maybe is empty";
}
}
}
答案 0 :(得分:1)
public Maybe filter(Predicate pred)
您的filter
方法采用raw谓词并返回原始Maybe
。
这意味着它期望谓词适用于任何对象,并且给出一个Maybe
,其中可能包含任何类型的对象。
应该是
public Maybe<T> filter(Predicate<? super T> pred) {
if (isPresent() && !pred.test(cont)) {
return new Maybe<T>();
}
return this;
}
因此,它将仅接受适用于泛型类型T
的谓词,并返回一个Maybe
,该谓词只能包含类型为T
的对象。
您的map
函数也是错误的。
public <R> Maybe <T> map(Function<T, R> func)
这假设在您的T
应用于func
之后,您将拥有Maybe<T>
。但是实际上您将拥有一个Maybe<R>
,因为R
是func
的产物。
这会更有意义:
public <R> Maybe<R> map(Function<T, R> func) {
if (isPresent()) {
return new Maybe<R>(func.apply(cont));
}
return new Maybe<R>();
}
这是工作代码:
jshell> String txt = "Hi";
txt ==> "Hi"
jshell> String msg = Maybe.of(txt).filter(t -> t.length() > 0).orElse("Empty");
msg ==> "Hi"
jshell> txt = "";
txt ==> ""
jshell> msg = Maybe.of(txt).filter(t -> t.length() > 0).orElse("Empty");
msg ==> "Empty"