5 ms·
() is the unit/void value. The void value isn't a concept that most languages have, so the syntax may be unfamiliar, but it's really useful and once you have it
by pcwalton 10y ago
() is the unit/void value. The void value isn't a concept that most languages have, so the syntax may be unfamiliar, but it's really useful and once you have it it's annoying to work with languages that don't have it.
- nostrademons 10y agoIt's actually fairly common in modern languages, particularly in expression-oriented languages. Haskell, Ocaml, Swift, and Scala spell it (). Python spells it None. Kotlin spells it Unit(). In Kotlin and Python, it is implied whenever you do 'return' without a value, which is a pretty handy way of bridging programmers' understanding of it when they come from older programming languages (eg. Java and C) that don't have it.
- Jweb_Guru 10y agoPython's None is closer to null than unit.
- adrusi 10y agoThere isn't really a meaningful distinction in a dynamically typed language. Null is a value that indicates the absence of something else that could be there instead, Unit is essentially the lack of any value. So when a python function implicitly returns None whenever it's called, that's semantically more similar to Unit than Null.
- kazagistar 10y agoThe difference is methods. A Result or Option has methods like map that let you transform it regardless of which case it is in, while a null will always crash unless you match on it first.
- adrusi 10y agoIn that case, do you condsider Go's nil to not be a null, since you can call methods on it that can do whatever? Or how about objective C's nil, where any messages sent to it are simply ignored? Edit: I see now that you're talking about the difference between null and Result/Option, not the difference between null/Option and Unit, so we're talking about different things. Semantically, a value that could be data or null is equivalent to an option type. Option types have methods, yes, but that's just a superficial convenience facility, you could implement the same thing for nullable types by writing a function: public static <A, B> B map(A object, Function<A, B> f) { if (object == null) return null; return f.apply(object); }
- Sean1708 10y agoPython also has (). >>> type(()) <class 'tuple'>