What does that 2 dots mean? What is the difference between 1 and 2? - dart

I have seen a lot of tutorials using dot, while some use 2. What is the actual meaning of this?
Example,
Array().add()
Animation()..addListener(() {})

The .. operator is dart "cascade" operator. Useful for chaining operations when you don't care about the return value.
This is also dart solution to chainable functions that always return this
It is made so that the following
final foo = Foo()
..first()
..second();
Is strictly equals to this:
final foo = Foo();
foo.first();
foo.second();

Just to be a nitpicker, .. isn't actually an operator in Dart, just part of Dart's syntactic sugar.
In addition to the mentioned use of cascades for chaining calls to functions, you can also use it to access fields on the same object.
Consider this code, taken from the Dart documentation:
querySelector('#confirm') // Get an object.
..text = 'Confirm' // Use its members.
..classes.add('important')
..onClick.listen((e) => window.alert('Confirmed!'));
The first method call, querySelector(), returns a selector object. The code that follows the cascade notation operates on this selector object, ignoring any subsequent values that might be returned.
For more information about cascades, check out Dart's outstanding documentation!

Related

What does it mean <> in method?

I have this method
#override
Response<BodyType> convertResponse<BodyType, SingleItemType>(
Response response) {
final Response dynamicResponse = super.convertResponse(response);
final BodyType customBody =
_convertToCustomObject<SingleItemType>(dynamicResponse.body);
return dynamicResponse.replace<BodyType>(body: customBody);
}
What does it mean <BodyType> and <BodyType, SingleItemType> in this method?
These are called generics in Dart (in fact, they are called the same in other similar programming languages).
The main idea behind generics is that you could reuse the same code without relying on a specific data/return type. Imagine List in Dart. You could have a list of integers (List<int>), a list of strings (List<String>), a list of your custom objects (List<CustomType>) - the type is not hardcoded and it could be adjusted based on your needs.
Also, you could say that it would be easier just to use dynamic or Object types that would cover most of these cases. However, generics brings you type safety, and the method type itself becomes a parameter.
Here is the official documentation about generics.

Does dart have an equivalent to C# discards?

C# discards prevent allocation of values not needed. Is there something similar in dart? I saw a lot of people use the underscore as if it were a discard, but using two at the same time (like this (_, _) => method() will say the variable _ is already defined.
Dart does allow you to use the same discard operator as C#. You can define a variable or final with a name of _. This works well with the rule avoid-ignoring-return-values (Dart Code Metrics) Importantly, if you name the variable with this, you will not encounter the warning unused-local-variable. However, there is another code rule called no_leading_underscores_for_local_identifiers. You can safely turn this off as long as you don't have someone in your team that has a habit of prefixing variable names with an underscore.
Ignoring the return value
Discarding the return variable
Unfortunately, it doesn't work the same way as C# because it involves an assignment, and you cannot assign two different types to it. You need to declare it as an Object?

In Dart's Strong-Mode, can I leave off types from function definitions?

For example, I'd like to just be able to write:
class Dog {
final String name;
Dog(this.name);
bark() => 'Woof woof said $name';
}
But have #Dog.bark's type definition be () => String.
This previously wasn't possible in Dart 1.x, but I'm hoping type inference can save the day and avoid having to type trivial functions where the return type is inferable (the same as it does for closures today?)
The language team doesn't currently have any plans to do inference on member return types based on their bodies. There are definitely cases like this where it would be nice, but there are other cases (like recursive methods) where it doesn't work.
With inference, we have to balance a few opposing forces:
Having smart inference that handles lots of different cases to alleviate as much typing pain as we can.
Having some explicit type annotations so that things like API boundaries are well-defined. If you change a method body and that changes the inferred return type, now you've made a potentially breaking change to your API.
Having a simple boundary between code that is inferred and code that is not so that users can easily reason about which parts of their code are type safe and which need more attention.
The case you bring up is right at the intersection of those. Personally, I lean towards not inferring. I like my class APIs to be pretty explicitly typed anyway, since I find it makes them easier to read and maintain.
Keep in mind that there are similar cases where inference does come into play:
Dart will infer the return type of an anonymous function based on its body. That makes things like lambdas passed to map() do what you want.
It will infer the return type of a method override from the method it is overriding. You don't need to annotate the return type in Beagle.bark() here:
class Dog {
String bark() => "Bark!";
}
class Beagle extends Dog {
final String name;
Dog(this.name);
bark() => 'Woof woof said $name';
}

What does "to close over the enclosing scope/class" mean?

The Akka documentation is documenting dangerous variants of using Props:
// NOT RECOMMENDED within another actor:
// encourages to close over enclosing class
val props7 = Props(new MyActor)
Then carries on stating:
This method is not recommended to be used within another actor because
it encourages to close over the enclosing scope, resulting in
non-serializable Props and possibly race conditions (breaking the
actor encapsulation).
Could someone please explain the meaning of "closing over the enclosing scope"? Been looking all over and found nothing. Thanks.
It's a bit tricky to see in this example, that the new Actor is passed in as a so called "by name" parameter. Think of it as if it is turned into a function of type () => Actor. This function will be called every time the actor will be (re)created by it's supervisor during a restart.
The problem is that this function is a "closure" (very easy to Google ;)), which means it captures and remembers everything in the surrounding scope that it needs (sometimes, but very rarely referred to as "stack ripping"). E.g val f = (a: Int) => a + x. Where does the x come from? It comes from the surrounding scope. The function litetal, assigned to f is called an "open term". At runtime the function literal becomes a function value (that's a fancy way of saying "object"), which when executed closes the open term, while capturing everything in the surrounding scope. That's where the name "closure" comes from.
Closures are very very useful, but you have to be careful what you close over. Sometimes x is a def or god forbid a var, which leads to unpredictable results for f, because you don't have control over the time when f will be called/executed. Try it out!
Two very common anti paterns in Akka are/were:
Closing over (the outer) this reference when creating an Actor
from an inner class.
Closing over def sender when responding to
a message with a future.
I gave you a bunch of fancy terms to Google on purpose, btw ;)
Cheers and happy coding
As a supplement to #agilesteel's fine answer, some references:
Explains what closures are: Programming in Scala, 8.7, Closures
Explains why closures can cause serialization problems: SIP-21 - Spores
And here is a code example of creating a Props object that is not serializable because of closing over a non-serializable object, based on the example in SIP-21:
case class Helper(name: String)
object MyNonserializableObject {
val helper = Helper("the helper")
val props7 = Props(new MyActor(helper))
}
Even though helper itself is serializable, the "new MyActor(helper)" is passed by name and so captures this.helper, and this is not serializable.
You can see that the actor parameter is passed by name from the signature of the Props apply method where there is a ⇒ in the creator parameter:
def apply[T <: Actor](creator: ⇒ T)(implicit arg0: ClassTag[T]): Props

Ruby Integer(), Array(), et al -- what are they? Where do they come from?

I've come across conversions of the form Array(value), String(value), and Integer(value) on occasion. It appears to me that these are just syntactic sugar for a call to the corresponding value.to_a, value.to_s, or value.to_i methods.
So I'm wondering:
Where/how are these are defined? I can't find them in Object, Module, Class, etc
Are there any common scenarios for which it's preferable to use these rather than the corresponding/underlying to_X method?
Could these be used in type-generic coercion? That is, can I do something along the lines of
[Integer, String, Array].each {|klass| klass.do_generic_coercion(foo) }
? (...and no, I don't really want to do that; I know the type I want out, but I'm looking to avoid the case statement.)
This is a good and difficult question. Let's answer the three parts.
First part
To find the definition, it is important to realize that the name of the method is "Array", etc., which can be quite counterintuitive, since methods are usually lowercase...
irb> method(:Array)
=> #<Method: Object(Kernel)#Array>
This tells you these are defined in Kernel, and thus available everywhere without requiring an explicit prefix.
Second part
Array(), String(),... are conversion methods. Calling obj.to_a will return an array, but will raise an NoMethodError if obj doesn't respond_to? :to_a. So the typical case when you'd prefer using Array(), String(), instead of to_a or to_s is when you are not positive an object responds to a given conversion method.
String(obj) will return nil if obj doesn't respond_to? :to_s. String(obj) will also check that the result of to_s is actually a string; it should be, but maybe an overly creative programmer decided to return something else?
Most other conversion methods act the same way, but Array(obj) is different. It will return [obj] if obj doesn't respond_to? :to_a. It will actually call to_ary (which is the implicit conversion operation, while to_a is the explicit one).
There is another important way to convert objects in 1.9 (and upcoming 1.8.8): Array.try_convert(obj). This returns nil if the obj does not respond_to? :to_ary. It will not call the to_a. Although they are longer to type, you might prefer using them when writing very general code that might accept different types of objects and want to avoid converting a hash to an array by mistake, for example (since Hash has a to_a method but not to_ary). When your method requires an array-like object and you are willing to do an explicit conversion, then obj.to_a is fine. The typical use of Array(obj) would be in a method that accepts either a single obj to act on, or a list of objects (although typically this is written as [*obj]).
Last part
Hopefully, the answers to the first two parts give you your final answer...
You can use:
[Integer, String, Array].each {|klass| klass.try_convert(foo) }
or
[:Integer, :String, :Array].each{|method| send(method, obj)}
Good question! Let's see if we can figure it out.
Ross-Harveys-MacBook-Pro:ruby-1.9.1-p376 ross$ irb
irb(main):001:0> Object.ancestors
=> [Object, Kernel]
irb(main):002:0> Kernel.ancestors
=> [Kernel]
irb(main):003:0> Kernel.class
=> Module
irb(main):004:0> Kernel.public_methods.include? "Array"
=> true
So, it looks like these are methods in the Kernel module that are mixed in to Object, so they are available without specifying a receiver. We might also want to peek at the C implementation, in object.c:
VALUE
rb_Array(VALUE val)
{
VALUE tmp = rb_check_array_type(val);
if (NIL_P(tmp)) {
tmp = rb_check_convert_type(val, T_ARRAY, "Array", "to_a");
if (NIL_P(tmp)) {
return rb_ary_new3(1, val);
}
}
return tmp;
}
One thing seems easy to conclude, the default .to_a is deprecated, so it does seem like Array(x) is the canonical way to do the conversion. It apparently does nothing if given an Array, calls .to_a if that's present, and if not it just wraps its argument in an Array.
Regarding whether to_a is deprecated...well, I said "the default":
Ross-Harveys-MacBook-Pro:puppet_sd ross$ irb
irb(main):001:0> class X; X; end.new.to_a
(irb):1: warning: default `to_a' will be obsolete
They are Defined in Ruby Kernel Module, like:
Array(), Complex(), Float(), Integer(), Rational(), Stirng(), etc.
I found those method references in Dave Thomas's Pickaxe book "Progamming Ruby 1.9", page 555.
For example: Array(arg) will convert arg as an Array, following are copied from the book:
"Returns arg as an Array. First tries to call rg.to_ary, then arg.to_a. If both fail, creates a single element array containing arg( or an empty array if arg is nil)."
ex. Array(1..5) # => [1, 2, 3, 4, 5]
From what I understand, the simple version is like this:
object.to_a tries to convert 'object' to an Array using a class member function.
Array(object) tries to make a new Array using 'object'.
I can re-define what .to_a means for a given class (it is just another member after all). The Array(...) call is defined in Kernel so it behaves the same for any class. I typically use type conversions of the style Array(...) when I don't know ahead of time what type of object will be passed in. It's better at handling cases where an object doesn't know how to convert itself to an array or can't be converted to an array. If the object to be converted is the result of a long or complex expression, using the Array(...) style is often clearer. I save the .to_a form for instances when I know the class of the object and exactly what to expect from the output of .to_a (mostly instances when I have written or modified the .to_a member function myself).

Resources