So, to denote that a function returns no value we ...
# announcements
m
So, to denote that a function returns no value we use
Unit
. How should I denote that a parameter takes no value?
Unit
or
Nothing?
? That’s relevant in a generic context like
Visitor<Result, Data>
where some visitors need no input and hence use
Unit
or
Nothing?
as
Data
.
s
The
Unit
type has one single possible instance (
Unit
), while
Nothing
has no value instances. With that in mind,
Unit -> A
is a function that doesn't require anything interesting to produce an
A
, while
Nothing -> A
is a function that can never be called because it's not possible to create the argument instance to call it with.
m
The choice is between
Unit
and
Nothing?
, i.e. an optional
Nothing
. Both have exactly one value:
Unit
has
Unit
and
Nothing?
has
null
.
s
Sorry, I missed the “?”. In that case, if I understand the intent correctly, I’d recommend Unit because “Nothing?” can only ever be null and so the function is only ever called with null. I find Unit conveys the same intent more clearly.
m
Yeah I thought so too. I’m surprised that Kotlin compiler code uses
Nothing?
in that case so I think it’s a topic worth discussing 😄
s
Interesting, it may be an optimisation?
m
Maybe. Or maybe because
Unit
means there’s a value (
Unit
) and
null
better represents the absence of a value.
s
I’d personally find Unit to better represent the absence of any meaningful value, but... ¯\_(ツ)_/¯
m
yeah ¯\_(ツ)_/¯