Witam,
mam problem z następującym programem:
public class Main {
@SuppressWarnings({ "unchecked"})
public static void test() {
// Metoda of(...)
String s = "aaa";
Maybe<String> m1 = Maybe.of(s);
System.out.println(m1);
s = null;
Maybe<String> m2 = Maybe.of(s);
System.out.println(m2);
// Metoda ifPresent(...)
Integer num = null;
@SuppressWarnings("unchecked")
Maybe<Integer> m4 = Maybe.of(num);
if (num != null)
System.out.println(num);
m4.ifPresent(n -> System.out.println(n));
m4.ifPresent(System.out::println);
Maybe<Integer> m5 = Maybe.of(10);
m5.ifPresent(System.out::println);
// Metoda map()
Maybe<Integer> m6 = m5.map(n -> n + 10);
System.out.println(m6);
// Metoda get()
System.out.println(m6.get());
try {
System.out.println(m4.get());
} catch (Exception exc) {
System.out.println(exc);
}
// Metoda orElse()
String snum = null;
if (num != null)
snum = "Wartość wynosi: " + num;
if (snum != null)
System.out.println(snum);
else
System.out.println("Wartość niedostępna");
String res = Maybe.of(num).map(n -> "Wartość wynosi: " + n).orElse("Wartość niedostępna");
System.out.println(res);
// I filter(...)
String txt = "Pies";
String msg = "";
if (txt != null && txt.length() > 0) {
msg = txt;
} else {
msg = "Txt is null or empty";
}
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();
}
}
```
program ma zwraca następujący wynik na konsoli:
Maybe has value aaa Maybe is empty 10 Maybe has value 20 20
java.util.NoSuchElementException: maybe is empty Wartość niedostępna Wartość
niedostępna Pies
oraz klasa Maybe:
``````java
import java.util.NoSuchElementException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
public class Maybe<T> {
Maybe m;
T t;
public Maybe() {
m = new Maybe();
}
public Maybe(T t) {
this.SetParam(t);
}
public static <T> Maybe<T> of(T t){
Maybe<T> maybe = new Maybe<>();
maybe.setParam(t);
return maybe;
}
private void setParam(T t) {
t = this.t;
}
public void ifPresent(Consumer cons) {
if (m != null) {
cons.accept(m);
} else {
}
}
<R> Maybe<R> map(Function<T, R> func) {
if (t != null)
return new Maybe<R>(func.apply(t));
return new Maybe<R>(null);
}
public T get() {
if (m == null) {
throw new NoSuchElementException();
} else {
return t;
}
}
public boolean isPresent() {
if (m != null) {
return true;
} else {
return false;
}
}
public T orElse(T defVal) {
if (m == null) {
return defVal;
} else {
return t;
}
}
public Maybe filter(Predicate pred) {
if (pred.test(pred) == true) {
return m;
} else {
m = new Maybe();
return m;
}
}
}
```
Przy próbie kompilacji, otrzymuje dwa błędy przy kompilacji linii
```java
msg = Maybe.of(txt).filter(t -> t.length() > 0).orElse("Txt is null or empty");
```
The method length() is undefined for the type Object oraz Type mismatch: cannot convert from Object to String
scibi92