I had saved a variables name and value to a JSON file in Dart. Later I extracted the name and value from that JSON file and now am trying to create a new variable with that name. Something like this:
var variableName= "firstName";
String variableName = "Joe";
so that:
String firstName = "Joe";
Is there a way to do this?
Short answer: No.
You cannot create variables at runtime in Dart. The compiler assumes that all variables are visible when the program (or any single method) is compiled.
The way variables are looked up in Dart is that "x" refers to a local, static or top-level variable, if there is such a variable in the lexical scope, and it refers to "this.x" if there is variable in the lexical scope named "x".
If you could add a variable later, you would be able to change "x" from meaning "this.x" to meaning something else. Already compiled code would then be incorrect.
Related
I am learning dart and this behavior of dart is annoying me
var a=10;
a="John"; //it generates an error, because a has integer data-type and we can't assign
//string or the value of any other data type because we have assigned an
//integer value
but at the same time, dart allows us to write
var a;
a=10;
a="John";
print (a) //it displays John
it means that we can't assign the value of any other data type when a variable initializes at the time of declaration but we can assign the value of any other data type if the variable declares in one line and initializes at the second line. Why does dart work in this way?
The var keyword is used to let Dart automatically assign a type for the variable based on the value you are using to initialize the variable.
If you use var without providing any initial value, the type of your variable are automatically being assign to dynamic which allows any type of object to be assigned to the variable. But it also means your program are much less type safe since the analyzer can no longer help you with what type the variable are going to return and what types are allowed when setting the variable.
So in your first example, a is being assigned the type int since you provide 10 as the initial value. It is therefore a compile error when you are trying to set a String as the new value of your int variable.
In your second example, a is going to be dynamic since you are not providing any initial value. So it is not a problem to first give it 10 and later 'John' since dynamic allow us to use any type. But that also means that when we try to use a in our program, Dart cannot make any guarantees about what type of object you are going to get so errors will first be identified at runtime.
That's because var means dart will assign the type of variable itself.
In first case, the dart assigned variable a as int type because it was given a value during initialisation.
But in second case, the dart assigned variable a as dynamic and that's why you can assign it either a string or int later on.
Is it possible to get the type of a variable in Dart at run-time, without having it assigned to an instance of an object and without using mirrors?
I know I can do this without mirrors (which is great!):
Foo foo;
foo = new Foo();
var fooType = foo.runTimeType; // This will give me a type of "Foo"
But I want to know the type of the variable before it is assigned to an object:
Foo foo;
var fooType = foo.runTimeType; // This will not give me a type of "Foo"
I am guessing it is not possible since the typing info is lost in run-time but would like to have it confirmed.
(My actual scenario is that I am doing dependency injection into a Polymer Element using Custom Events. I would like to put as much of this code as possible in an element base-class and have as little code as possible in each derived element class. One thing that I need to do this is to know the type of variables that are to be injected).
I'm just wondering. As I understand, var and let can be anything and Swift automates the right type like in JavaScript. But when I try to set properties in a class I get an error when I don't specify the type.
var value1, value2 // Error: missing annotations
Well, I've read some references and the variable requires a type on declaration like var foo = 0. But in my class I have an init() which will set the variables to whatever I input when creating the object of the class.
So how should I achieve this? Is it even possible?
I saw the type typealias but that didn't work either.
While both Swift and Javascript allow you to assign constants to variables without defining their type, there is a fundamental difference in the two languages. Swift is a strongly-typed, type-safe language while Javascript is not. From The Swift Programming Language -
“Swift is a type safe language. A type safe language encourages you to
be clear about the types of values your code can work with. If part of
your code expects a String, you can’t pass it an Int by mistake.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
https://itunes.apple.com/au/book/swift-programming-language/id881256329?mt=11
So when you say
var welcomeMessage = "Hello"
Swift infers that you want welcomeMessage to be a string and sets its type accordingly. Subsequently trying
welcomeMessage=3
will give run a compile-time error because you are assigning the incorrect type.
If you don't assign an initial value then Swift can't infer the type and you must specify it.
Javascript, on the other hand, will quite happily accept
var welcomeMessage="Hello"
welcomeMessage=3
because it isn't type safe and just tries to do the best it can with values it has. For example, if a string operation is performed on welcomeMessage after assigning 3 to it, Javascript would convert the value to "3" and then perform the operation.
While there are type safe extensions to Javascript, it isn't a fundamental part of the language the way it is with Swift
The types are only inferred if you assign a default value initially. From an example in the Language Reference, either declare the type:
var welcomeMessage: String
or assign an initial value that allows Swift to infer the type:
welcomeMessage = "Hello"
In the welcomeMessage example above, no initial value is provided, and so the type of the welcomeMessage variable is specified with a type annotation rather than being inferred from an initial value.
JavaScript is dynamically typed, meaning variables don't have a type assigned to them. Types are only associated with objects. So a variable can contain objects of any type.
Swift is statically typed on the other hand. Meaning variables have type. You can't place any object you want into a variable. The compiler will make sure you only place compatible objects into variables.
Swift has type inference which allow the compiler to figure out the type if you write:
var value1 = "foobar"
But just writing var value1 wouldn't let the compiler figure out what type the value1 variable is. JavaScript doesn't have this problem since variables don't have types.
Remember similar looking syntax does not mean the same semantics. Swift might look a bit like JavaScript syntax wise, but the meaning (semantics) of the keywords is quite different. If you want to simulate JavaScript:
var value1, value2
In Swift you would write:
var value1: AnyObject
var value2: AnyObject
That would allow you to put any object into the value1 and value2 variables.
I have been using XOM parser in a project that is mostly over. The parser is very good and I find it mostly stable. However today I was parsing an XML element with an attribute called "xml:lang"
The getAttributeValue("xml:lang") returned null instead of "English". I could find a work around to get the value by using getAttribute(int location).getValue()
However, it would be better to use the method getAttributeValue because the attribute's location changes for other elements.
I am not sure whether I am doing something wrong or a small bug lies there in the library method.
The xml:lang attribute is in a namespace.
To get the value of an attribute in a namespace, use the Element.getAttributeValue(String, String) method. The first parameter needs to be the local name of the attribute (after the colon), which is lang in this case. The second parameter needs to be the URI of the namespace, which is usually defined in an ancestor element. The xml namespace, however, is built in and always has the namespace URI http://www.w3.org/XML/1998/namespace.
Therefore, some code like this should do what you want (assuming you have a variable called element pointing to your element):
String lang = element.getAttributeValue("lang", "http://www.w3.org/XML/1998/namespace");
I was looking through the docs for instance_variable_set and saw that the sample code given does this:
obj.instance_variable_set(:#instnc_var, "value for the instance variable")
which then allows you to access the variable as #instnc_var in any of the class's instance methods.
I'm wondering why there needs to be a colon : before the #instnc_var. What does the colon do?
My first instinct is to tell you not to use instance_variable_set unless you really know what you are using it for. It's essentially a tool for metaprogramming or a hack to bypass visibility of the instance variable.
That is, if there is no setter for that variable, you can use instance_variable_set to set it anyway. It's far better if you control the code to just create a setter.
Try looking at accessors for the vast majority of your instance variable setting needs. They are an idiomatic way to have getters and setters for your instance variables "for free" without you having to write those functions.
If you really do need instance_variable_set, it allows the first argument to be a symbol which is the name of the instance variable to set. A colon is part of the Ruby language that is like a "symbol literal": when you type :foo, you've created a symbol with value foo, just like when you type "bar" directly into your code, you create a string literal with value "bar".