Are all data types a specific type of an class? - class

if all data types of dart language is class so
why when it's not assigned like that
int y = int(); or int(45);
String x = String(); or String ('Ahmed');
it's confused me

All Dart values are objects.
All non-function values are instances of a specific class and implements a number of interfaces.
(Function values can technically be seen as each having their own class, but in practice those classes don't really exist. Function values still implement the class interfaces Function and Object.)
Dart classes can have different constructors. There is no rule that a Dart class must have an unnamed constructor taking zero or one arguments.
If you write int y = int();, you get an error because the int class does not have an unnamed zero-argument constructor.
The same way int(45) is invalid because the int class doesn't have an unnamed one-argument constructor.
(The only constructor the int class has is int.fromEnvironment, which is an external const factory constructor. You can read that as it being "magic".)
Similarly, the String class does not have an unnamed constructor taking zero or one arguments, so you can't write String() or String('Ahmed'). Not because it's invalid syntax, it's just trying to call a constructor which does't exist.
The String class has String.fromCharCode/String.fromCharCodes as constructors that you can use.
You seem to be assuming that because something, X, is a class, you can write X() or X(someXValue). That's just not true in Dart. You have to look at each class to see which constructors it actually has.

Related

Better practice in list/array initialization

In creating a not-null empty list or array, which is advised between these two.
List newList = List();
List<Obstacle> obstacles = List<Obstacle>();
or
List newList = [];
List<Obstacle> obstacles = [];
or they both do the exact same thing and have the same effect on processing and memory.
Declarative vs. Literal Constructors
From my knowledge, there isn't any difference between using a literal constructor, [] and a declarative constructor List().
Both have the same result, but I would suggest that you use the declarative List() constructor. Because the literal constructor is used for predefining a few values in a list. Like: List myList = [1,2,3];.
So if you want to create a non-null list, use:
List myList = List();
But if you want to define some initial values for your list, then use the literal constructor:
List myList = [1,2,3];
Generics
Quick Info: Lists are generics, Maps are also Generics.
A Generic is basically when you want to pass an Object Type as a parameter to a class or function or type definition. Smart programmers use this to write reusable code.
For example, I have a Response class which I use all over my app, the Response class has a data variable. But I want it to be able to tell Dart where the Response class carries a data of type String or a data of type int.
So to achieve this I would make my Response class a Generic.
Here is an example of a Generic response class. The data variable can be set as needed for any situation in my app.
Response<String> response = Response<String>();
//Defining a Generic's type is optional.
//So both statements work.
Response response = Response();
class Response<T> {
T data;
}
Why Generics?
So that you get Dart's amazing static compile safety features. Generics give the flexibility of reusing a class for multiple situations but still give you powerful compile safety.
So when declaring a List if you define that it's a List<int>. The compiler will make sure that you don't accidentally try inserting a String in it.

Why are auxilary constructors forced to call the main constructor in Scala?

... and supply it with all necessary arguments even if they where not required for the auxiliary constructor. (Source: http://joelabrahamsson.com/learning-scala-part-four-classes-and-constructors/) This is not the case in Java. What is the reasoning behind that?
In Scala, the primary constructor's parameters are available anywhere inside the class (among other reasons, so you don't have to repeat Java's this.x = x; this.y = y; this.z = z;). If the parameter isn't used, it has no reason to be a parameter in the first place, so consider only the case where it is used. So if you could avoid supplying these parameters, and then got to the place where they are used, what should happen?
The compiler could use default values (null/0/false/etc), which is very likely not what the user wants. Or throw an exception, turning a compilation error into a runtime error, which is the opposite of what we want.
Easy: if a parameter is not required, don't add it to the main constructor.
In java, all constructors also execute the code in the body of the class:
public class Foo {
String x = mkX();
public Foo() { System.out.println("THIS"); }
public static String mkX() { System.out.println("THAT"); return "";}
}
new Foo(); // prints THAT, then THIS
The requirement in scala is actually more relaxed: your main constructor is allowed to have arguments.

How to force a val in a class to be immutable in class using class type in OCaml

Let's say I have this :
class type point_t =
object
val x : int
method getx : int
method move : int -> unit
end;;
I can write a class like this and it will work :
class point : point_t =
object
val mutable x = 0
method getx = x
method move d = x <- x + d
end;;
Now suppose that I want to create a class type that would NOT allow a class to be defined with a mutable val x (I want x to be immutable). Is there a way to do that ?
It is not possible, so if you don't want to allow implementations to use a mutable variable it is better just to hide it all and expose functional getter/setter:
class type point_t = object(self)
method get_x : int
method with_x : int -> self
method move : int -> self
end;;
You may omit with_x method if you want to allow updates only via the move method.
The reasoning for this is that a class with a mutable version of a variable is a proper subclass of a class with immutable version of the same variable, as it has the same set of operations, plus one more - an ability to set the variable. So, any abstraction over a type point_t can be applied to a class instance with and without a mutability (although it will not be able to mutate the variable). Note, that the opposite is not possible, if you will define the class type point_t with a mutable x, and will try to implement it with an immutable one, then the type system will complain. As your implementation doesn't provide all the operations.
Also, there is one thing that you possibly miss. Although, the class point has a mutable variable x this mutability is actually sealed (i.e., hidden) by the type constraint point_t. So, no matter what is the implementation, the interface is strictly defined to have immutable x:
class the_point = object
inherit point
method! move d = x <- x - d
end
method! move d = x <- x - d
^^^^^^^^^^
Error: The instance variable x is not mutable
Your confusion may arise from the fact that you have some experience with Java/C++ style of OOP, where class types are nominal, and a class can became a subclass of another class only by explicit inheritance. In OCaml a class is a subclass of another class if it is a syntactical superset of it, i.e., if it has at least all fields of the super class. There is no need to inherit from a super class, to become its subclass. And class point : point_t is not an inheritance, but a type constraint, that says: here is the class expression, that implements point_t class (and maybe more), please, make sure that it is true and expose only point_t interface to the outsiders.
And a final note, I've specifically denoted term sub classing as the syntactic super set of a super class to emphasize the fact that inheritance and sub classing do not imply subtyping. The latter is the semantics (i.e., the behavior of an instance), the former is syntax, i.e., a set of code fragments. Subclassing gives you a code reuse, the ability to copy the code from superclasses (as inherit is actually just copy/pasting the code of super class to your sub class). The subtyping gives you the polymorphism - an ability to use the same abstraction on different implementations.

Scala class constructor local parameters

Can I pass arguments to Scala class constructor that are not stored into class itself?
I want to achieve functionality which in Java could be written as follows:
class A {
private final SomethingElse y;
public A(Something x) {
y = x.derive(this);
}
}
I.e. class constructor takes parameter that is later transformed to another value using reference to this. The parameter is forgotten after constructor returns.
In Scala I can do:
class A(x: Something) {
val y = x.derive(this)
}
But it means that x is stored in the class, which I want to avoid. Since x.derive method uses reference to this, I can not make the transformation in companion object.
But it means that x is stored in the class, which I want to avoid.
If you don't reference constructor argument anywhere except the constructor itself, field won't be created. If you reference x e.g. in toString(), Scala will automatically create and assign private val for you.
Use javap -c -private A to verify what kind of fields are actually created.
BTW you pass this inside a constructor, which means a.derive() gets a reference to possibly non-initialized instance of A. Be careful!

Creating and using a generic function in a non generic F# interface

It is beyond me at this point. I'm trying to create an interface that looks something like
this.
type IFetchData =
abstract FetchData: string -> seq<'a>
The above declaration is valid (and compiles) but when I go to use it I get a compile time error. This expression was expected to have type 'a but here has type "what I'm currently trying to return" i.e. seq.
My example usage however looks like the following:
type SampleFetchData() =
interface IFetchData with
member self.FetchData str =
seq {
for letter in str do
yield letter // compile error here
}
I'm not sure what I'm doing wrong. All I'd like to do is allow the interface implementer to be able to write any function that returns a generic sequence either seq<string>,seq<int>,seq<record type here>, seq<union type here>, etc.
Can someone tell me what I'm missing here?
Thanks.
If you're loading the interface implementation using Reflection, then it is going to be quite difficult to work with it. The problem is that you get an object of type obj. You know that it implements IFetchData<'T> for some 'T, but statically, you don't know for which 'T. This is a problem because you can't cast the object to any more specific type - if you tried using IFetchData<obj>, it wouldn't work because you can't cast, for example, IFetchData<int> to that type.
I would recommend using a non-generic interface, which is quite common .NET pattern:
type IFetchDataUntyped =
abstract FetchData : string -> System.Collections.IEnumerable
type IFetchData<'T> =
inherit IFetchDataUntyped
abstract FetchData : string -> seq<'T>
When you load an implementation using Reflection, you can cast the object to IFetchDataUntyped and work with it in a fairly reasonable way (using Seq.cast to convert the sequence to a more specific type if you know the element type).
Depending on your application, you may also just make the FetchData method a generic method and keep the interface non-generic. Then you could cast dynamically loaded objects to the interface and invoke the method. However, this changes the design (because the method has to work for any type it gets as a type parameter):
type IFetchData =
abstract FetchData<'T> : string -> seq<'T> // Note: Generic parameter here!
You need to do something like
type IFetchData<'a> =
abstract FetchData: string -> seq<'a>
type SampleFetchData() =
interface IFetchData<char> with
member self.FetchData str =
seq {
for letter in str do
yield letter
}
i.e. the interface needs to be made generic. If you want to avoid the genericness you could use some inline constraints, rather than an interface
EDIT: Inline magic version
let inline Fetchdata string obj=
(^a: (member FetchData: string -> seq<'b> )(obj, string))
type SampleFetchData() =
member self.FetchData str =
seq {
for letter in str do
yield letter
}
Fetchdata "hello" (new SampleFetchData())