14

Optional is useful in an obvious way in a statically typed language, but I'm wondering if it's also useful in dynamic languages. Usually there's no compiler telling you, "hey, you used this Optional<String> as a String", so you still have to discover your mistakes at runtime. I have a static typing background and from my perspective I can't see the benefit of an Optional type in a dynamic language.

13

That weakness is really no different than for all types in dynamic languages. You have to run it to find out what's in it. Options aren't really different in that regard.

Options are more than just a static annotation that a value may or may not be present. They have operations associated with them as well. Chains of mapped operations on options are one highly useful feature, that keeps you from having to check for failure after every step in the chain.

Even if you only immediately retrieved the value, it still would prod the programmer to check for Nothing the first time it ran and failed. Without an option, that prodding would only take place if it happened to contain null the first time you ran it. Many a null pointer dereference have stubbornly waited until the product was in the field.

0

I can talk for Objective-C.

Since dynamic typed languages bind late, checking for an "optional" (a non-value is represented with nil) is inherent: If you check for the type at runtime, you check for nil implicitly. Of course this is chainable. This is done inherently, too.

For static typed languages this extra concept is a benefit, because they have to take the type decision at compile time – a situation dynamic typed languages never have.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.