Dynamically access property using variable - vala

How does one retrieve a property from an object when the name of that property name is a variable?
Simply using the following doesn't seem to work
object[prop_name]
In this case it's to dynamically retrieve a value from a GLib.Object after it changed:
device.notify[prop_name].connect((s, p) => {
debug (" updated: %s", device[prop_name]);
});

The following seems to work
string value;
device.get (prop_name, out value);
debug (" update: %s", value);

Related

How do I check whether a generic type is nullable in Dart NNBD?

Let's say I had some function that takes a generic type as an argument. How do I check within that function whether the generic type argument is nullable or not? I want do something like this:
void func<T>() {
print(T is nullable);
}
void main(){
func<int>(); //prints false
func<int?>(); //prints true
}
All I can think of to do is to check if T.toString() ends with a ? which is very hacky.
Try:
bool isNullable<T>() => null is T;
The accepted answer really just checks if the type can be null. It doesn't care about the type that you are operating the null operator on.
If you want to check if a type is a specific nullable type, a.k.a if you want to check if a type is specifically one of type DateTime? and not String?, you can't do this in dart via T == DateTime? as this conflicts with ternary operator syntax.
However, since dart allows passing nullable types into generic arguments, it's possible to it like so:
bool isType<T, Y>() => T == Y;
isType<T, DateTime?>() works.
I have come across this a lot. And #Irn method works, except for when T is type Type (when using generics), it will always return saying that T is not null.
I needed to test the actual type of Type not Type its self.
This is what I have that is working really well for me.
bool get isNullable {
try {
// throws an exception if T is not nullable
final value = null as T;
return true;
} catch (_) {
return false;
}
}
It creates a new List instance to verify if it's type is nullable or not by using the is operator which supports inheritance:
bool isNullable<T>() => <T?>[] is List<T>;

What does the exclamation mark mean before a function call?

I was following a PR for Flutter and came across this code:
if (chunkCallback != null) {
chunkCallback!(0, 100);
}
What does the exclamation mark mean after chunkCallback? Nothing I search on Google works.
"!" is a new dart operator for conversion from a nullable to a non-nullable type.
Read here and here about sound null safety.
Use it only if you are absolutely sure that the value will never be null and do not confuse it with the conditional property access operator.
chunkCallback is a nullable reference to a function.
If you are sure that chunkCallback can't be null at runtime you can "Cast away nullability" by adding ! to it to make compiler happy
typedef WebOnlyImageCodecChunkCallback = void Function(
int cumulativeBytesLoaded, int expectedTotalBytes);
...
class Class1 {
final WebOnlyImageCodecChunkCallback? chunkCallback;
Class1(this.chunkCallback);
void test() {
if (chunkCallback == null) {
throw Exception("chunkCallback is null");
}
chunkCallback!.call(0, 100);
}
}
Esentially, ! in this case is a syntactic sugar for
(chunkCallback as WebOnlyImageCodecChunkCallback).call(0, 100);
I think it is a shorthand syntax for “Casting away nullability”, as per the docs: https://dart.dev/null-safety/understanding-null-safety#null-assertion-operator
The variable chunkCallback must be able to accept null and you cannot call a function on a nullable type without either using ! or ?. This is part of Darts sound null safety
Some great videos on this:
Flutter vid
YouTube vid
Even though the conditional statement checks for null, Dart still requires the exclamation mark before the function call. The difference between using ! over ? is that it will throw an exception instead of using the variable if the value is null.
Some examples:
class Car {
String? make; // String or null type
Car([this.make]); // parameter is optional
}
main() {
Car test = Car('Ford'); // initialised with a value
Car test2 = Car(); // no value given so null is default
// returns 4
if (test.make != null) {
print(test.make!.length); // ! still needed even though !=null condition stated
} else {
print('The value is null');
}
// returns The value is null
if (test2.make != null) {
print(test2.make!.length);
} else {
print('The value is null');
}
}
Above example shows that conditional check for null is not enough.
And choosing between ? and !
class Customer {
String? name;
String? surname;
Customer(this.name, [this.surname]); // constructor with optional parameter []
}
main() {
Customer ford = Customer('John'); //only name is given a value
// calling a method on a nullable type doesn't work
// so ? and ! used here after variable name and before method
print(ford.name!.length); // operation executed as usual => 4
print(ford.surname?.length); // ? on null value returns null => null
print(ford.surname!.length); // Exception is thrown => TypeError
}

Display template not called if TypeConverter exists

As soon as I register a TypeConverter for a complex type, it fails to load the correct (base type) display template for properties of a derived type, i.e., #Html.DisplayFor(m => m.My_Derived_ComplexTypeProp) fails to load the MyComplexType display template.
I've debugged the display template selection logic a little bit, and the problem seems to be very obvious:
// From TemplateHelpers:
internal static IEnumerable<string> GetViewNames(ModelMetadata metadata, params string[] templateHints)
{
[...]
yield return fieldType.Name; // TRY 1: Type, but no base type walking
if (!(fieldType == typeof (string))) // YEP ...
{
if (!metadata.IsComplexType) // Unfortunately YEP (see below...)
{
if (fieldType.IsEnum) // NOPE
yield return "Enum";
else if (fieldType == typeof (DateTimeOffset)) // NOPE
yield return "DateTime";
yield return "String"; // TRY 2: string => uh oh, string will be found, and we do not use the correct display template.
}
[...]
else
{
[...] // only in here we would have the base type walk
}
[...]
// From ModelMetadata:
public virtual bool IsComplexType
{
get
{
// !!! !!! WTF !!! !!!:
// Why is IsComplexType returning false if we cannot convert from string?
return !TypeDescriptor.GetConverter(this.ModelType).CanConvertFrom(typeof (string));
}
}
As soon as the logic detects "no complex type" it simply checks for enumerations, DateTimes and returns the template for string otherwise! But look at the implementation of IsComplexType -> if convertible to string it is treated like a simple type!
So, of course, as soon as you register a type converter for a complex type, the display template resolution fails to use the correct template.
Is there a known workaround? I cannot believe, I'm one of the few people running into this until now...
I have found Cannot use TypeConverter and custom display/editor template together?, however, the "solution" which is marked as answer, is not really a solution. It just hackarounds the problem...

SYMFONY FORM ChoiceType, multiple=>true. How to by pass the need to implement Data Transformers

In a SYMFONY FORM (ORM is not use (PDO is used for DB query instead)).
I have a class MyEntityType in which the buildForm function has:
$builder->add('my_attribute',ChoiceType::class,array(
'choices'=>$listForMyAttribute,
'multiple'=>'true',
'attr'=>array('data-native-menu'=>'false'),
'label'=>'Multiple Select on my attribute'
));
My attribute is an array of an entity named MyEntity which has:
/**
* #Assert\NotBlank()
*/
private $myAttribute;
With a getter and a setter for that variable $myAttribute.
When I submit the form in the Controller, it doesn't pass the validation check and logs this error:
Unable to reverse value for property path "myAttribute" : Could not find all matching choices for the given values.
When I start to look for solution around this error message, it leads to something named "How to Use Data Transformers" in SYMFONY Cookbook; And it seems a solution would involve to create new Class and write a lot of code for something that one should be able to by-pass in a much straight forward way.
Does anyone have an idea?
My problem was that my array $listForMyAttribute was defined in the buildForm() function and its definition was relying on some conditional.
The conditional to make the array were met when this one was displayed for the first time.
After pushing the submit button, the buildForm was regenerated in the Controller, this second time, the condition were not met to make the array $listForMyAttribute as it was on the first display. Hence the program was throwing a "contraint not met error" because the value submited for that field could not be find.
Today I face exactly the same problem. Solution is simple as 1-2-3.
1) Create utility dummy class DoNotTransformChoices
<?php
namespace AppBundle\DataTransformer;
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface;
class DoNotTransformChoices implements ChoiceListInterface
{
public function getChoices() { return []; }
public function getValues() { return []; }
public function getPreferredViews() { return []; }
public function getRemainingViews() { return []; }
public function getChoicesForValues(array $values) { return $values; }
public function getValuesForChoices(array $choices) { return $choices; }
public function getIndicesForChoices(array $choices) { return $choices; }
public function getIndicesForValues(array $values) { return $values; }
}
2) Add to your field the following additional option:
...
'choice_list' => new DoNotTransformChoices,
...
3) Congratulations!

Grails : Overriding getter method in domain class

I can't override grails getter method and becoming crazy.
What I want is use a double value and a string value to get a formatted data, but when I'm typing my override method into String, the double value is null and when into double, it obviously get me an error because a String is returned !
I get a domain class like that :
class Project {
...
String currency
Double initialTargetAmount
...
}
First Override method (initialTargetAmount is null in this case) :
//#Override Comment or uncomment it does not make any change to the behaviour
public String getInitialTargetAmount() {
println "${initialTargetAmount} ${currency}" // display "null EUR"
"${initialTargetAmount} ${currency}" // initialTargetAmount is null
}
Second method :
//#Override Comment or uncomment it does not make any change to the behaviour
public Double getInitialTargetAmount() {
println "${initialTargetAmount} ${currency}" // display "1000.00 EUR"
"${initialTargetAmount} ${currency}" // Error : String given, Double expected
}
Any help is welcome.
Snite
Groovy has dynamic getters and setters.
So, initalTargetAmount field "creates" automatically a Double getInitialTargetAmount method. Which is why it works when you have the Double return Type. But when you set String, getInitialTargetAmount automatically refers to a field String initalTargetAmount which doesn't exist
Try changing the name of the method, for example getInitialAmountWithCurrency() and it will work. Maybe your best bet will be to override toString() method ^^
Your getter should be always the same type of your field, and it's noot a good approach to change the getter like this, because Grails (Hibernate internally) will understand that your object instance changed and will try to update it ( it will check the old and new values).
You're trying in fact is to have a String representation of your amount, so you have a couple of options to this:
1 - A new method
Creating a new method that returns String will not interfere in the hibernate flow and you can use it anywere.
class Project {
...
String currency
Double initialTargetAmount
...
String displayTargetAmount() {
"${initialTargetAmount} ${currency}"
}
}
2 - TagLib
Depending on your needs, you could create a TagLib to make this custom representations of your class. This can include html formatting.
class ProjectTagLib {
static namespace = "proj"
def displayAmount = { attrs ->
if(!attrs.project) {
throwTagErrro("Attribute project must be defined.")
}
Project project = attrs.remove('project')
//just an example of html
out << "<p>${project.initialTargetAmount} , ${project.currency}</p>"
}
}

Resources