Can we make a parameter compulsory on conditions?

Viewed 76

As we know we can use ternary operator like ? and : in Dart for control flow, like :

String name  = 1 == 1 ? "Jhon" : "Ryan";

Is there anyway to make a parameter compulsory on condition ?

The Codes Below Did Not Work, It's Here Just For The Example

class Person{
  final String name;
  final int age; 
  const Person({ this.name, name != null ? @required this.age : this.age});
}
2 Answers

No you cannot do this.

You can have asserts checking conditions, but that would be runtime, not compile-time.

Your best way to make it happen is indeed having different named constructors for different purposes.

With the coming null-safety feature it would be a nightmare anyway. Not necessarily for the compiler, but for the programmer who has to understand it.

Annotations like @required can only be added statically, and not depending on conditions.

To me this looks like a case for asserts as mentioned by @nvoigt

class Person{
  final String name;
  final int age; 
  const Person({ this.name, this.age}) : assert(name != null || age != null, "either name or age must be provided");
}
Related