Defining property in constructor - dart

I'm trying to do something that would be a basic feature in any other Object Oriented Language but for some reasons in Dart, I can't manage to do it. I'm new to Dart so this question might be dumb, but I couldn't find any answer online.
I have a property that need to be calculated once and on the constructor. This is my code so far :
class Game {
String _wordChosen;
Game() {
final _random = Random();
_wordChosen = WORDS[_random.nextInt(WORDS.length)];
}
}
WORDS is a list defined outside the class. My error is on the Game constructor :
not_initialized_non_nullable_instance_field.
I don't want to set the _wordChosen variable to a default value as that would make no sense (it would be overwritten right when the constructor is run).
I also don't want to set the property as nullable as again, it would make no sense.

i think the answer is using the keyword late to make compiler know that you will initialize the variable before using it but not now like below
late String _wordChosen;
i think this is your solution and it in null safety documents here
i hope this answer helps you

Related

Super simple but hard question for a Dart beginner

I am trying to learn Dart language. Following code seems very straight forward but does not work. I know it may be a foolish question for an expert but for me hard to understand why not ?
class Car{
carFun(){
print("Test");
}
}
main(){
Car.carFun();
}
Already answered but I'll give more context.
You need to mark your method as static:
static carFun(){ ...
This makes the method available as a 'Class Method'; right now, as you have defined it, it is an 'Object Method'. This means that you need to make an object out of the class Car to be able to use it, which would be something like this:
var myCar = new Car();
myCar.carFun();
This way you instantiated an object and used a defined method for it. Marking it as static would make this approach not work. This is one of the many differences between a Class and an Object.
Mark your method as static. Read more: https://dart.dev/guides/language/language-tour#class-variables-and-methods

Why does an unitialized typed variable in Dart not implement the type's interface?

I started learning Dart and was reading a critique of some of it's design choices here: https://medium.com/#krossovochkin/dart-language-bad-design-choices-6e35987dc693
The last point that is made is about the poor type system and the author cited this code snippet which prints null:
void main() {
String s = null;
if (s is String) {
print("string");
} else if (s is Null) {
print("null");
} else {
print ("none");
}
}
The is keyword was new to me but "The Dart Programming Language" by Gilad pointed out that is checks the interface implemented by an object's class and not the actual class of an object.
However this didn't help me much because I would think that the variable s is an instance of String and therefore implements String, but the evidence is to the contrary.
I get that the class is not required when defining objects/variables in Dart, and thus I started to wonder if putting the class in the definition just serves as sugar and has little functional purpose. But instead the class of an object/variable is completely determined by its value, and since the default value for all variables in Dart is null, then it would make sense that String is not implemented, but Null is. Is this the case? Am I way of base? Maybe someone could help me wrap my head around this.
The reason is that is checks the interface of the current object itself and not the reference to this object. So yes, s can point to a String object but also allowed to point to null which are a instance of Null: https://api.dart.dev/stable/2.7.2/dart-core/Null-class.html
Since Null does not implement the String interface, this will return false (null is String). This is also mentioned in the article.
The problem the article are trying to focus on are more the fact you are allowed to set the String variable to null value but Null does not implement String.
Well, in the future, this problem are going to be fixed with non-nullable types which are in development right now. When this is implemented you can actually define variables where you can be sure the value will never be null.
So I continued my Dart reading and I came to a better understanding, and that is that Dart is truly optionally typed and that means 2 things:
Type are syntactically optional.
Type has no impact on runtime semantics.
Therefore the actual type annotation of a variable in Dart only serves documentation purposes and it cannot be assumed that a type annotation is true. The actual type of a variable is wholly determined by the value stored at this variable, and in this case it is null.
In truth the variable that I defined in my example is not a String variable or an implementer of the String interface. It is just annotated that it may be/should be/most likely is a string.

Definitionless, private function

I am new to dart, and I am not familiar with this concept. Some patience is appreciated.
I was reading some code, here, when I came across this. (line 14)
static final none = Motility._(0);
Looking at the second half of the assignment, I can see a private function that takes an integer, but after some searching I do not see a definition in the class.
So, my question is what is this mysterious function? I am assuming this is a feature of the language, but I am having trouble looking it up since I have never heard of this concept!
It invokes the constructor
Motility._(this._bitMask);
https://github.com/munificent/hauberk/blob/master/lib/src/engine/stage/tile.dart#L28
It is not that obvious anymore since new became optional, but it is a common pattern to have private constructors. (Identifiers starting with _ are private in Dart)
Motility is basically an enum that is built this way instead of
enum Motility { none, door, fly, swim, walk, doorAndFly, doorAndWalk, flyAndWalk }
because this way custom values can be assigned.

What are the conventions in Dart about class members' encapsulation and type annotations?

I am new to Dart language. So I would like to know more about some conventions that programmers follow while developing in this language.
Should I always encapsulate my class members as I do, for example in Java? Whenever I create property of class, should I make it private and provide getters/setters? Or there are situations when I should leave them public? If so, what are examples of these situations?
In my opinion, type annotations such as String, int, etc. increase readability of code. They serve as a documentation for other developers who are reading/using my code. Programmer should not think value of what type is storing in this variable right now. So again, what are the situations, that require using var keyword when declaring a variable?
Dmitry.
Thank you.
Thanks for checking out Dart!
No need to encapsulate class fields. Dart creates implicit getters and setters for you. If you need to actually compute something for that field, you can then implement the getter or setter manually. Bonus: this doesn't break consumers of your API.
Example:
class Person {
int age;
}
Later, you want to calculate age:
class Person {
DateTime birthdate;
int get age => new DateTime.now().difference(birthdate).inDays ~/ 365;
}
In both cases, you can do this:
print(person.age);
Pretty cool! No change in API, and no defensive getters and setters (just add them when you need them).
You should use type annotations for the "surface area" of your code. For example, use type annotations for method and function signatures. For cases where the variable's type is very obvious, you should consider using var, because it's more terse and readable.
For example:
String doCoolStuff(int bar) {
var clearlyABool = true;
return 'Hello world';
}
Note that the return type and bar parameter are type annotated, but the clearlyABool uses var because we initialize with a bool.
Feel free to use type annotations everywhere, it's programmer choice. Anecdote: the dart2js source code uses type annotations pretty much everywhere.

ActionScript: Constructor for Value Object classes

Is it OK to use the constructor to set properties for a value object class or must I use dot notation and set each one, one-by-one?
I recently read an article that was saying I should do it one-by-one as value objects should only contain properties and went on to say using the constructor is not OK (best-practice wise).
Code:
("not OK")
var employee=new
Employee(firstName,lastName,age);
("OK")
var employee=new Employee();
employee.firstName=firstName;
employee.lastName=lastName;
employee.age=age;
What's your take on this?
Thank you.
I've never heard anyone say that using a constructor to construct an object is a bad idea. The only case that I can think of is if the list of elements to be initialized can be changed (add/removed) and therefore changing the API of the object (which is bad, especially when developing libraries). In this case, I'd still use the constructor, but I'd pass in an initialization object (which contains n parameters) rather than modifying the function signature.
The statement "it's bad practice to use the constructor to construct the object" (paraphrasing) just doesn't make sense to me :P

Resources