site-www icon indicating copy to clipboard operation
site-www copied to clipboard

'A tour of the Dart language' page issue

Open SchmadenSchmuki opened this issue 5 years ago • 2 comments

Page URL: https://dart.dev/guides/language/language-tour Page source: https://github.com/dart-lang/site-www/tree/master/src/_guides/language/language-tour.md

Description of issue:

I had the unexpected behaviour of

for (double val in doubleList)
  val *= someFactor;

not changing the values of the entries in my doubleList. After that I read on stackoverflow that primitives will be passed by value.

Maybe this could be mentioned in the language tour, especially since

Everything you can place in a variable is an object, and every object is an instance of a class. Even numbers, functions, and null are objects. All objects inherit from the Object class.

gave me the impression val will be a reference (I still don't know what is considered a primitive in dart). Maybe I didn't read the tour thoroughly enough, I surely didn't learn dart thoroughly enough, just wanted to tell you my experience, not being sure if this is the right place.

Anyway, that's all I have to say about it, so this issue can be closed or deleted (duplicate, not right info for language tour, already written in the language tour).

SchmadenSchmuki avatar Apr 28 '20 14:04 SchmadenSchmuki

Thanks for the feedback. I'll think about how/where we can make this clearer.

kwalrath avatar Apr 28 '20 17:04 kwalrath

https://stackoverflow.com/questions/22210247/list-foreach-unable-to-modify-element seems to have good answers related to this. Basically, the variable (val above) doesn't actually refer to the item in the list; it just temporarily has the same value as the item.

To apply one of lrn's explanations to your example, when you say val *= someFactor, it's like saying this:

var z = val;
z *= someFactor;

To actually change list values, you'd use a method like map(), which returns a new (lazy) Iterable. The Iterables codelab shows how to use map().

All this isn't obvious, so I definitely want to make it clearer in the language tour.

kwalrath avatar Sep 17 '21 00:09 kwalrath