Q: why does Option::get() may return null?
nzour opened this issue · 3 comments
nzour commented
Just noticed that Option::get()
may return null value.
Are there any specific reasons for this behavior?
I mean, there are other implementations of Option
and non of them do return null value.
Java
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
Scala
def get: Nothing = throw new NoSuchElementException("None.get")
Rust
pub fn unwrap(self) -> T {
match self {
Some(val) => val,
None => panic!("called `Option::unwrap()` on a `None` value"),
}
}
Maybe there is a contract for Option
to have that kind of behavior?
whsv26 commented
There are cases like Option<non-empty-list<int>>
. You would expect to use $nonEmptyListOption->getOrElse([])
, but getOrElse
signature is
/**
* @psalm-param A $fallback
* @psalm-return A
*/
public function getOrElse(mixed $fallback): mixed
And psalm will issue an error cause of []
is not non-empty-list
. In this case it's convenient to use $nonEmptyListOption->get() ?? []
whsv26 commented
In scala getOrElse
default value type is supertype of option value type, but I don't see a way to implement this in psalm.
final def getOrElse[B >: A](default: => B): B
nzour commented
Got it, thanks for replying