Retrieve class parameter using a string in Dart - string

Let's say that I have a class in Dart that looks like this:
class Hello {
final name;
Hello({this.name});
}
I could create an instance of this class using:
var x = new Hello(name: "General Kenobi");
In Javascript, I could retrieve the name property with syntax like this:
console.log(x["name"]);
Is there a way to do the equivalent in Dart? I.e
print(x["name"]);
I've looked at the docs and can't find anything, would appreciate help from someone who knows. Many thanks.

The easiest way is to create a method, which converts a class to Map and overload [] operator:
class Hello {
final name;
Hello({this.name});
Map<String, dynamic> toMap() => {'name': name};
operator [](String field) => toMap()[field];
}

Related

Cucumber V5-V6 - passing complex object in feature file step

So I have recently migrated to v6 and I will try to simplify my question
I have the following class
#AllArgsConstructor
public class Songs {
String title;
List<String> genres;
}
In my scenario I want to have something like:
Then The results are as follows:
|title |genre |
|happy song |romance, happy|
And the implementation should be something like:
#Then("Then The results are as follows:")
public void theResultsAreAsFollows(Songs song) {
//Some code here
}
I have the default transformer
#DefaultParameterTransformer
#DefaultDataTableEntryTransformer(replaceWithEmptyString = "[blank]")
#DefaultDataTableCellTransformer
public Object transformer(Object fromValue, Type toValueType) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.convertValue(fromValue, objectMapper.constructType(toValueType));
}
My current issue is that I get the following error: Cannot construct instance of java.util.ArrayList (although at least one Creator exists)
How can I tell cucumber to interpret specific cells as lists? but keeping all in the same step not splitting apart? Or better how can I send an object in a steps containing different variable types such as List, HashSet, etc.
If I do a change and replace the list with a String everything is working as expected
#M.P.Korstanje thank you for your idea. If anyone is trying to find a solution for this here is the way I did it as per suggestions received. Inspected to see the type fromValue has and and updated the transform method into something like:
if (fromValue instanceof LinkedHashMap) {
Map<String, Object> map = (LinkedHashMap<String, Object>) fromValue;
Set<String> keys = map.keySet();
for (String key : keys) {
if (key.equals("genres")) {
List<String> genres = Arrays.asList(map.get(key).toString().split(",", -1));
map.put("genres", genres);
}
return objectMapper.convertValue(map, objectMapper.constructType(toValueType));
}
}
It is somehow quite specific but could not find a better solution :)

How does this groovy syntax translate to kotlin?

I created a simple Greeting task in Kotlin.
Just like the one in the gradle documentation.
Now I'm adding a simple test to it that looks like this in groovy:
class GreetingTaskTest {
#Test
public void canAddTaskToProject() {
Project project = ProjectBuilder.builder().build()
def task = project.task('greeting', type: GreetingTask)
assertTrue(task instanceof GreetingTask)
}
}
I translated this one into Kotlin except one single bit in this line:
def task = project.task('greeting', type: GreetingTask)
The problematic bit is the second parameter. type: GreetingTask
What does it exactly stand for and how does it translate into Kotlin?
Thx to Opal for leading me to the solution.
In addition to his answer here is the kotlin version of the test:
class GreetingTaskTest {
#Test
public fun canAddTaskToProject() {
val project = ProjectBuilder.builder().build()
val task = project.task(mapOf("type" to GreetingTask::class.java), "greeting")
assertTrue(task is GreetingTask)
}
}
Have a look at the docs. task method takes a String and a Map. greeting is an instance of String and type: GreetingTask is a named parameter which is converted to an instance of Map. So you should pass a Map as the second arg. Unfortunately, don't know how to declare a Map in kotlin. This method might be helpful.

Groovy - Is it possible to pass a class as a parameter?

This is just a very basic example of what I want to do. There's a bit more that goes on in the foobar method, but it's the gist of what I'm doing. It obviously doesn't work, since it fails to compile, but I'm wondering if I'm just passing the class incorrectly or using the 'className' parameter in the wrong way. I know I can rework it to take the string of the class name and just match it, but it seems a shame to do that. This would be so nice and DRY.
class Foo {
String name
}
class Bar {
String name
}
def foobar(field, className) {
def instance = className.findByName(jsonParams.field)
if(!instance) {
instance = new className(name: jsonParams.field)
}
return instance
}
foobar(foos, Foo)
foobar(bars, Bar)
I don't know much Java or Groovy, so I'm not sure what's possible vs impossible yet. Feel free to just tell me "No." I've tried googling and haven't found anything that really answers the question for me. A simple no would be great at this point haha.
Yes, it is possible to pass class as argument - in Groovy, classes are first class citizens (see this thread for more detail).
This construct: instance = new className(name: jsonParams.field) actually tries to create an instance of class named className, not of the class referenced by this variable. To make it compile, you need to call Class.newInstance:
class Foo {
String name
}
class Bar {
String name
}
def foobar(String name,Class clazz) {
def instance = clazz.findByName(name)
if(!instance) {
instance = clazz.newInstance(name:name)
}
return instance
}
foobar('foo', Foo)
foobar('bar', Bar)
​
I'm not entirely sure what you want to achieve with the findByName method, though - neither Foo nor Bar have a static method named findByName as far as I can tell.

Automapper: map List<string> to List<Class>

How can I map a List<string> to List<Class>?
Usecase: from the Webservice I'm getting a class with a list of string but in my MVC Viewmodel, I want to have Class instead with a single property, which has the value of the string. That way I can add Validation attributes to the property.
I have the way how I convert the List into a List, however I can't get the other way around to work.
Any simple solutions?
The way to do this with AutoMapper is to use .ConstructUsing:
Mapper.CreateMap<string, Class>()
.ConstructUsing(str => new Class { MyProp = str });
Example: https://dotnetfiddle.net/0Vlc8b
You can easily do it with Linq.
var newList = oldList.Select(x => new Item(x)).ToList();
You could do this:
void Main()
{
AutoMapper.Mapper.CreateMap<string,A>()
.ForMember(a => a.Name, m => m.MapFrom(s => s));
new[] {"A", "B"}.Select (AutoMapper.Mapper.Map<A>).Dump();
}
class A
{
public string Name { get; set; }
}
(Linqpad code)
But I think this can go down as a textbook example of over-engineering. Just do it as in Daniel's example.

Custom generic list of generic class

I got a class
public class ID_Name<T>
{
public ID_Name(T id)
{
this.ID = id;
}
public T ID { get; set; }
public string Name
{
get
{
return Helper.SomeReturnValue;
}
}
}
All I want to do is generate a custom List of ID_Name where I can pass an ID_Name.ID as parameter in Add.
I tried the following:
public class ID_Name_List<T> : IList<T> where T : ID_Name<T>
but then I get the following error:
The type "EProtokollStatus" cannot be used as type parameter "T" in
the generic type or method "ID_Name_List<\T>". There is no boxing
conversion or type parameter conversion from "EProtokollStatus" in
ID_Name<\EProtokollStatus>.
I read something about this issue here: No boxing or type parameter conversion for generic Type parameter but I can't see a restriction except ID_Name here.
This may be wrong somehow, because everything I want to express is "use the same type T as in ID_Name for ID_Name_List", but how do I achieve that?
I found something here: C#: Declaring and using a list of generic classes with different types, how? but I don't want to create many different classes for all possible types.
All I want to achieve is something like
ID_Name_List<EProtokollStatus> myList = new ID_Name_List<EProtokollStatus>();
myList.Add(EProtokollStatus.ValueX);
Your current constraint makes no sense. Did you mean:
public class ID_Name_List<T> : IList<ID_Name<T>>

Resources