Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you combine named parameter with short-hand constructor parameter?

Tags:

In dart:

Named parameters function like so-

String send(msg, {rate: 'First Class'}) {
  return '${msg} was sent via ${rate}';
}

// you can use named parameters if the argument is optional
send("I'm poor", rate:'4th class'); // == "I'm poor was sent via 4th class"

Short-hand constructor parameters function like so-

class Person {
  String name;

  // parameters prefixed by 'this.' will assign to
  // instance variables automatically
  Person(this.name);
}



Is there any way to do something like the below?-

class Person{
   String name;
   String age;

   Person({this.name = "defaultName", this.age = "defaultAge"});
}

//So that I could do something like:
var personAlpha = new Person(name: "Jordan");

Thanks,

Code samples borrowed from dartlang synonyms

like image 967
Jordan Avatar asked Feb 12 '14 07:02

Jordan


People also ask

Does Java support named parameters?

Java does not support Objective-C-like named parameters for constructors or method arguments. Furthermore, this is really not the Java way of doing things. In java, the typical pattern is verbosely named classes and members. Classes and variables should be nouns and method named should be verbs.

What are required parameters in Dart?

Dart required positional parametersWe declare required positional parameters with a type and name, e.g., int: a . The name is for reference in the function, not at the call site. You specify only the value without a parameter name when calling a function. int sum(int a, int b) { // 1.

What is the syntactic sugar concept in Dart constructor?

In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.


1 Answers

Update

Yes, the = is allowed in Dart 2 and is now preferred over the : to match optional positional parameters.

Person({this.name = "defaultName", this.age = "defaultAge"});

Old Answer

You just have to use a colon instead of equals

class Person {
   String name;
   String age;

   Person({this.name: "defaultName", this.age: "defaultAge"});
}

I find this still confusing that optional parameters use = to assign defaults but named use :. Should ask myself.

like image 89
Günter Zöchbauer Avatar answered Sep 20 '22 14:09

Günter Zöchbauer