Why direct usage of generic value is not possible but same is possible if returned from method in Dart - flutter

Why is it assigning a value to a generic field is not possible when assigned directly, but same is possible when using a variable reference or method return value (here, same value is assigned to the variable and method returns the same value)?
class User {}
class Teacher extends User {}
class Student extends User {}
Future<User> getUser() {
return Future.value(Student());
}
void main() {
Future<Future<User>> fut = Future.value(getUser()); // <----- No error
Future<Future<User>> fut2 = Future.value(Future.value(Student())); // <----- Getting error
Future<User> userFut3 = Future.value(Student());
Future<Future<User>> fut3 = Future.value(userFut3); // <----- No error
}
Getting below error when Future.value(Future.value(Student())) assigned directly.
Error: The argument type 'Student' can't be assigned to the parameter type 'FutureOr<Future<User>>?'.

The issue here is that the parameter of Future<T>.value has the type FutureOr<T>. It can be either a future or a value.
Also, Dart type inference works by "pushing down" a context type, then trying to make the expression work at that type, and finally pushing the final static type back up.
If an expression like Future.value(...) has a context type, the missing type argument is always inferred from the context type.
When you write
Future<Future<User>> fut2 = Future.value(Future.value(Student()));
the context type of the outer Future.value, the type we know it should have, is Future<Future<User>>. That makes its argument have context type FutureOr<Future<User>>.
The argument is Future.value(Student()), where we don't yet know anything about Student() because we haven't gotten to it in the type inference yet, we're still working out way down towards it.
A Future<X> can satisfy that FutureOr<Future<User>> in two ways, either by being a Future<User> or by being a Future<Future<User>>.
Type inference then guesses that it's the latter. It's wrong, but it can't see that yet. The way type inference works, it has to use the context type when there is one, but the context type is ambiguous, and it ends up choosing the wrong option.
You are hitting an edge case of the type inference where the context type can be satisfied in two different ways, and the downwards type inference chooses the wrong one. It's a good heuristic that if you have a FutureOr<...> context type, and you see a Future constructor, you want the Future-part of the FutureOr<...>. It breaks down when you have FutureOr<Future<...>>. So, don't do that!
My recommendation, in complete generality, is to never have a Future<Future<anything>> in your program. Not only does it avoid problems like this, but it's also a better model for your code.
A future which eventually completes to something which eventually completes to a value ... just make it eventually complete to that value directly. Waiting for the intermediate future is just needless busywork.

Because in the function you defined the return type and dart knows the return type, but when assigning directly dart does not know Future.value(Student()) has a type of Future<User>. to fix this you have to tell the dart the type of the value, like this: Future.value((Future.value(Student())) as Future<User>);
this way dart will know the type of this value and treat it as a Future<User>.

Related

Dart/Flutter : The meaning of "whether some code is annotated or inferred is orthogonal to whether it is dynamic or some other type"

https://dart.dev/guides/language/effective-dart/design#types
If the code is type annotated, the type was explicitly written in the
code.
If the code is inferred, no type annotation was written, and Dart
successfully figured out the type on its own. Inference can fail, in
which case the guidelines don’t consider that inferred.
If the code is dynamic, then its static type is the special dynamic
type. Code can be explicitly annotated dynamic or it can be inferred.
In other words, whether some code is annotated or inferred is
orthogonal to whether it is dynamic or some other type.
The above explanation is extremely abstract and I'm not sure exactly what this means.
Especially the last sentence, does it mean that "it may be inferred as another type even though it is type-annotated as'dyanmic'"?
But maybe I feel it's not right.
Because I remember being told by the IDE during development that something like "because it's a dynamic type, you can't access that member."
If not, I would like a more specific explanation of what it means after all.
It would be helpful if you could get some clues.
Basically, a variable can be type annotated:
int x = 1;
also, it can be inferred:
var x = 1; // dart knows x is an integer because you assigned 1 to it.
A variable can be dynamic, meaning it's type can change.
That's what the three first sentences mean, the last sentence is saying that a dynamic variable can be either inferred or annotated:
dynamic someFunction() {
return 1;
}
dynamic x = 'aaa'; // annotated
var y = someFunction(); // inferred
So weather a variable is annotated or inferred has nothing to do with weather it is dynamic or not.

Swift generics: How to represent 'no type'?

I am using Google's promises library, and I would like to create promise without any type (because I don't need any).
However, I am being forced to pick some type:
let promise = Promise<SomeType>.pending()
Is there a type I could pass in place of SomeType that would essentialy mean 'no type', when I need promises just for async flow and exception catching, but I don't want to return a specific value from a function?
For example, some type whose only valid value is nil?
I have encountered this problem in multiple places, the only workaround I found so far is to always provide a non-generic alternative, but it gets really tedious and leads to duplicate code.
Types are sets of values, like Int is the set of all integer numbers, String is the set of all sequences of characters and so on.
If you consider the number of items in the set, there are some special types with 0 items and 1 items exactly, and are useful in special cases like this.
Never is the type with no values in it. No instance of a Never type can be constructed because there are no values that it can be (just like an enum with no cases). That is useful to mark situations, code flow etc as 'can't happen', for example the compiler can know that a function that returns Never, can never return. Or that a function that takes Never can never be called. A function that returns Result<Int, Never> will never fail, but is in the world of functions returning Result types. But because never can't be constructed it isn't what you want here. It would mean a Promise that can't be fulfilled.
Void is the type with exactly 1 value. It's normally spelled () on the left and Void on the right, of a function definition. The value of a void is not interesting. It's useful to make a function that returns Void because those are like what other languages call subroutines or procedures. In this case it means a Promise that can be fulfilled but not with any value. It can only be useful for its side effects, therefore.
Is it a correct solution or a workaround if we create an empty class
class Default_Class : Codable {
}
and use this as Promise<Default_Class>.pending

The name 'string' isn't a type and can't be used in an 'is' expression

During unit testing of a function returning different types of objects, I need to check if the type of returned object is the same as expected. Therefore, I need to pass multiple classes inside a variable. Then I need to use this variable with the is operator to check types.
final string = String;
assert('foo' is string);
But I am getting
error: The name 'string' isn't a type and can't be used in an 'is' expression.
I read somewhere that a library called Dart:mirrors can solve this problem but I haven't seen an actual example.
In unit testing, you know the expected answer. There shouldn't be a need to make your types variables.
Instead, just assert with the strong typed
assert('foo' is String);
I found the answer. The trick to create an instance of the type that I want to assert, then use runtimeType property.
If a class is called User from a.dart and another one is also called User from b.dart, runtimeType won't be the same
final string = 'anything'.runtimeType;
assert('foo'.runtimeType is string);

Usages of Null / Nothing / Unit in Scala

I've just read: http://oldfashionedsoftware.com/2008/08/20/a-post-about-nothing/
As far as I understand, Null is a trait and its only instance is null.
When a method takes a Null argument, then we can only pass it a Null reference or null directly, but not any other reference, even if it is null (nullString: String = null for example).
I just wonder in which cases using this Null trait could be useful.
There is also the Nothing trait for which I don't really see any more examples.
I don't really understand either what is the difference between using Nothing and Unit as a return type, since both doesn't return any result, how to know which one to use when I have a method that performs logging for example?
Do you have usages of Unit / Null / Nothing as something else than a return type?
You only use Nothing if the method never returns (meaning it cannot complete normally by returning, it could throw an exception). Nothing is never instantiated and is there for the benefit of the type system (to quote James Iry: "The reason Scala has a bottom type is tied to its ability to express variance in type parameters."). From the article you linked to:
One other use of Nothing is as a return type for methods that never
return. It makes sense if you think about it. If a method’s return
type is Nothing, and there exists absolutely no instance of Nothing,
then such a method must never return.
Your logging method would return Unit. There is a value Unit so it can actually be returned. From the API docs:
Unit is a subtype of scala.AnyVal. There is only one value of type
Unit, (), and it is not represented by any object in the underlying
runtime system. A method with return type Unit is analogous to a Java
method which is declared void.
The article you quote can be misleading. The Null type is there for compatibility with the Java virtual machine, and Java in particular.
We must consider that Scala:
is completely object oriented: every value is an object
is strongly typed: every value must have a type
needs to handle null references to access, for example, Java libraries and code
thus it becomes necessary to define a type for the null value, which is the Null trait, and has null as its only instance.
There is nothing especially useful in the Null type unless you're the type-system or you're developing on the compiler. In particular I can't see any sensible reason to define a Null type parameter for a method, since you can't pass anything but null
Do you have usages of Unit / Null / Nothing as something else than a
return type?
Unit can be used like this:
def execute(code: => Unit):Unit = {
// do something before
code
// do something after
}
This allows you to pass in an arbitrary block of code to be executed.
Null might be used as a bottom type for any value that is nullable. An example is this:
implicit def zeroNull[B >: Null] =
new Zero[B] { def apply = null }
Nothing is used in the definition of None
object None extends Option[Nothing]
This allows you to assign a None to any type of Option because Nothing 'extends' everything.
val x:Option[String] = None
if you use Nothing, there is no things to do (include print console)
if you do something, use output type Unit
object Run extends App {
//def sayHello(): Nothing = println("hello?")
def sayHello(): Unit = println("hello?")
sayHello()
}
... then how to use Nothing?
trait Option[E]
case class Some[E](value: E) extends Option[E]
case object None extends Option[Nothing]
I've never actually used the Null type, but you use Unit, where you would on java use void. Nothing is a special type, because as Nathan already mentioned, there can be no instance of Nothing. Nothing is a so called bottom-type, which means, that it is a sub-type of any other type. This (and the contravariant type parameter) is why you can prepend any value to Nil - which is a List[Nothing] - and the list will then be of this elements type. None also if of type Option[Nothing]. Every attempt to access the values inside such a container will throw an exception, because that it the only valid way to return from a method of type Nothing.
Nothing is often used implicitly. In the code below,
val b: Boolean =
if (1 > 2) false
else throw new RuntimeException("error")
the else clause is of type Nothing, which is a subclass of Boolean (as well as any other AnyVal). Thus, the whole assignment is valid to the compiler, although the else clause does not really return anything.
In terms of category theory Nothing is an initial object and Unit is a terminal object.
https://en.wikipedia.org/wiki/Initial_and_terminal_objects
Initial objects are also called coterminal or universal, and terminal objects are also called final.
If an object is both initial and terminal, it is called a zero object or null object.
Here's an example of Nothing from scala.predef:
def ??? : Nothing = throw new NotImplementedError
In case you're unfamiliar (and search engines can't search on it) ??? is Scala's placeholder function for anything that hasn't been implemented yet. Just like Kotlin's TODO.
You can use the same trick when creating mock objects: override unused methods with a custom notUsed method. The advantage of not using ??? is that you won't get compile warnings for things you never intend to implement.

When do I have to specify type <T> for IEnumerable extension methods?

I'm a bit confused about the use of all the IEnumerable<T> extension methods, intellisense is always asking for <T>, but I don't think it's necessary to specify <T> at all times.
Let's say I have the following:
List<Person> people = GetSomePeople();
How is this:
List<string> names = people.ConvertAll<string>(p=>p.Name).Distinct<string>().ToList<string>();
different from this:
List<string> names = people.ConvertAll<string>(p=>p.Name).Distinct().ToList();
I think the two lines of code above are sxactly the same, now the question:
How do I know when to specify <T> and when to skip it?
The simplest way is obviously to omit it and see if it compiles.
In practice, you can omit type parameters wherever they are inferred; and they can normally be inferred when they are used in the type of a method parameter than you specify. They cannot be inferred if they're used only in the return type of the method. Thus, for example, for Enumerable.Select<T>, T will be inferred from the type of first argument (which is of type IEnumerable<T>). But for Enumerable.Empty<T>(), will not be inferred, because it's only used in return type of the method, and not in any arguments (as there are none).
Note that the actual rules are more complex than that, and not all arguments are inferable. Say you have this method:
void Foo<T>(Func<T, T> x);
and you try to call it with a lambda:
Foo(x => x);
Even though T is used in type of argument here, there's no way to infer the type - since there are no type specifications in the lambda either! As far as compiler is concerned, T is the same type x is, and x is of type T...
On the other hand, this will work:
Foo((int x) => x);
since now there is sufficient type information to infer everything. Or you could do it the other way:
Foo<int>(x => x);
The specific step-by-step rules for inference are in fact fairly complicated, and you'd be best off reading the primary source here - which is C# language specification.
This feature is known as type inference. In your example, the compiler can automatically determine the generic argument type implicitly for you because in the method call to ConvertAll, the parameter lambda returns a string value (i.e. Name). So you can even remove the <string> part of ConvertAll call. The same is with Distict(), as ConvertAll returns a List<string> and the compiler can declare the generic argument for you.
As for you answer, when the compiler can determine the type itself, the generic argument is redundant and unnecessary. Most of the times, the only place where you need to pass the generic argument is the declaration, like, List<string> list = new List<string>();. You can substitute the first List<string> with var instead or when you are using templates as parameters in lambdas too.