Is it possible to make sure a type parameter is no...
# announcements
k
Is it possible to make sure a type parameter is not
Nothing
at compile time?
s
I don’t think you can, since
Nothing
denotes the ‘empty-set’ which is a sub-set of all other possible sets. This means that
Nothing
is assignable to every possible type. It is ugly, but you could force a function or a class-constructor to take an input-parameter of type
T
. If
T
is provided a
Nothing
, you code won’t compile.
fun <T> someFunction(dummy: T)
, then calling
someFunction<Nothing>(…)
will never work, whatever you put in the spot of
, because
dummy
cannot be provided a value, since
Nothing
has no values in its set.
f
fun ƒ(x: Nothing?) { requireNonNull(x) }
hehehe
🔥 1
k
@Fleshgrinder That wouldn't work, as people would most likely pass null in it anyway and I like people to know something is wrong at compile time.
s
You can’t pass in
null
to a
Nothing
value.
k
I know
s
Ah… your comment was in answer to Richard’s answer… sorry..
f
You can pass null to nothing.
You can also return
Nothing?
.
You're basically saying that you never have any meaningful type other than null. Totally valid.
s
No, you can’t. You can pass
null
to a
Nothing?
, not to a
Nothing
.
f
But that's what my signature uses. 😉
I added hehehe because there is the null loophole so it's not fully up to what you want.
s
Yup, but the original question was about the non-nullable
Nothing
🙂
f
However, nothing can ever be nothing because it is nothing.
s
😄
f
Hence, you cannot check for it.
s
At least, that is something! 😄
f
Well, you basically know that nothing is ever nothing already without any check. 😉
k
The place it would be used is on a operator`-=
. If I could just return the type I could at least mark the rest of the function as never executed. But
-=` has to return
Unit
f
I don't fully understand but you can just return unit:
fun ƒ() = Unit