Closed toastanddrink closed 3 years ago
Hi! I guess u can change ur Optional.ofNullable() to Optional.of(), and you should use Optional.of() in ur Lazy.of() method as well. Hope this helps!
For NoSuchElementException, you should make use of orElseThrow()
in the Optional class. This should be put in your of()
method and not your get()
method.
Optional has a method orElseThrow() that returns the value if present and throws NoSuchElementException if empty
Hi, currently my of() is just
static <T extends Comparable<T>> Lazy<T> of(T v) {
return new Lazy<T>(()->v);
}
static <T extends Comparable<T>> Lazy<T> of(Supplier<T> s) {
return new Lazy<T>(s);
}
and im not v sure how to go about changing it without affecting the rest?
Hi, you can change your of() by trying to creating an Optional.of(v), and catch the exception thrown by this method. So basically inserting these lines of code before the return statement.
try { Optional<T> t = Optional.of(v); } catch (Exception e) { throw new NoSuchElementException("No value present"); }
For your of()
that takes in the Supplier, you can use Optional.ofNullable
to wrap your s in an Optional, and then use orElseThrow()
on it when you put it in the Lazy constructor.
For the NoSuchElementException
, you can change s
to Optional.ofNullable(s).orElseThrow()
. For the NullPointerException
, you can change return v
to return value.orElseThrow(() -> new NullPointerException())
.
thank u all of you guys for the help!
Hi, does anyone know how to throw a NoSuchElementException for this? Previously the exception was thrown but as I proceeded higher on to the other levels the exception is not thrown anymore and I wonder why?
Thank you in advance!