Returning null in Constructor

354 views
Skip to first unread message

stackiller

unread,
Jan 5, 2021, 3:44:03 AM1/5/21
to Dart Misc
Hello, I hope you are all well.

Recently a situation made me think about the possibility of returning null in a builder.

The sample code below describes a package API that provides a generic Wrap class that initializes a variable with the type specified in the type annotation:


But, according to the code, it would not make sense to create an instance of the Wrap class if the type provided was different from String or int, accidentally passing the Map type or any other would generate errors, since the '+' operator is not implemented in the class Map.

It is currently possible to restrict the parameterized type, but nothing like: <T extends type0, type1>

The question is:

Would it be possible to do a parameterized type check and return null if the type provided is not what was expected?

Jacob Bang

unread,
Jan 5, 2021, 4:01:39 AM1/5/21
to mi...@dartlang.org
I think it would be very confusing if calling a constructor (or
factory constructor) could end up returning a null object. If an
object cannot be instantiated by the constructor, it should instead be
an exception which can then then be handled.

An alternative solution would be to make a static method in your class
which can then be used to create the object (maybe make the
constructor private). This static method could be called "tryWrap" (I
am bad at naming things...) and can have the signature "Wrap?
tryWrap(T a)" which makes it clear that the method can return null.
This design can e.g. be seen on int.tryParse().
> --
> For more ways to connect visit https://dart.dev/community
> ---
> You received this message because you are subscribed to the Google Groups "Dart Misc" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.
> To view this discussion on the web visit https://groups.google.com/a/dartlang.org/d/msgid/misc/5eccbe38-0958-45dd-b767-03f7a9a3b03en%40dartlang.org.



--
Jacob Bang / julemand101

stackiller

unread,
Jan 6, 2021, 11:15:39 AM1/6/21
to Dart Misc, julem...@gmail.com
Really, according to what i googled, throwing an exception if an object cannot be instantiated by the constructor makes more sense than returning null.

This question was also raised in Stackoverflow:

Thanks for the reply Jacob Bang.
Reply all
Reply to author
Forward
0 new messages