Dart abstract static method - dart

I want to create an abstract Sort class for my class project using dart which I will extend with Sorting algorithm classes like MergeSort, QuickSort, Heap, etc. I wrote the below code but I cannot create an abstract static sort method which I can override and use like
Heap.sort(arr)
OR
MergeSort.sort(arr)
Do anyone know why I cannot create abstract static method and also if you have any other way of doing this please feel free to guide me :D
abstract class Sort {
// void sort(List array);
static void sort(List array);
bool isSorted(List array) {
for (int i = 0; array.length > i - 1; i++) {
if (array[i] > array[i + 1]) {
return false;
}
}
return true;
}
void swap(arr, i, j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

As the answer linked above says, you can't have abstract static methods.
An abstract method does just one thing, it adds a method signature to the interface of the class, which other (non-abstract) classes implementing the interface then has to provide an implementation for. The abstract method doesn't add implementation.
Static methods are not part of the interface, so being abstract and static means it has no effect at all. It's a method with no implementation, which nobody can ever implement. So you're not allowed to do that.
To actually have separate classes representing different sorting algorithms, just do that directly using instance methods. That's the strategy object pattern.
abstract class Sorter<T> {
void sort(List<T> values);
int compare(T value1, T value2);
void swap(List<T> values, int index1, int index2) {
T tmp = values[index1];
values[index1] = values[index2];
values[index2] = tmp;
}
}
abstract class HeapSort<T> extends Sorter<T> {
void sort(List<T> values) {
// heap sort algorithm.
}
}
abstract class MergeSort<T> extends Sorter<T> {
void sort(List<T> values) {
// merge sort algorithm.
}
}
mixin ComparableSorter<T extends Comparable<T>> on Sorter<T> {
int compare(T value1, T value2) => value1.compareTo(value2);
}
class ComparableHeapSort<T extends Comparable<T>>
extends HeapSort<T> with ComparableSorter<T> {}
class CustomCompareHeapSort<T> extends HeapSort<T> {
int Function(T, T) _compare;
CustomCompareHeapSort(int Function(T, T) compare) : _compare = compare;
int compare(T value1, T value2) => _compare(value1, value2);
}
There are plenty of options about how to slice the API and abstract over different parts of it.
I recommend figuring out what use-cases you want to support, before starting the API design.

Related

Better solutions to long pattern matching chains (for Dart)

I've often found myself having to use annoying patterns like:
ClassA extends BaseClass {
static bool is(val) { ... }
}
ClassB extends BaseClass {
static bool is(val) { ... }
}
...
ClassZ extends BaseClass {
static bool is(val) { ... }
}
BaseClass parser(val) {
if(ClassA.is(val)) {
return ClassA(val);
} else if(ClassB.is(val)) {
return ClassB(val);
...
} else if(ClassZ.is(val)) {
return ClassB(val);
}
}
This is very error prone and requires a lot of monotonous code.
I was wondering if there was a way to expedite this process in a non-language specific (or in a language specific for Dart) way that doesn't involve listing all the pattern matchers after they've been defined. I would like to avoid this as I had too many bugs to count caused by forgetting to list one of the already defined class's pattern matcher.
If you want to cut down the arbitrary conditionals in the BaseClass.parser(), you can use a map as follows:
typedef Specification = bool Function(dynamic val);
typedef Factory = BaseClass Function(dynamic val);
class BaseClass
{
static final Map<Specification, Factory> _factoryMap = {
(val) => val == 'Hello': (val) => ClassA(),
(val) => val == 'There': (val) => ClassB(),
};
static BaseClass? parse(dynamic val)
{
for(var key in _factoryMap.keys)
{
if(key(val)) return _factoryMap[key]!.call(val);
}
throw ArgumentError('No valid factory found!');
}
}
class ClassA extends BaseClass
{ }
class ClassB extends BaseClass
{ }
class ClassC extends BaseClass
{ }
In Python, you can extend type and register the subclass's own specification method without manually listing like this. But I am not aware of such runtime meta programming in Dart for the time being. Maybe you can use source_gen in Dart to generate the conditionals automatically.
Combining the check with the construction of the object would help slightly. That would reduce the potential of accidentally using the wrong check and constructor, and it would reduce the amount of code you'd need to add outside of the class definitions:
ClassA extends BaseClass {
/// Attempts to return a [ClassA] if possible.
///
/// Returns `null` if inappropriate.
static ClassA? tryFrom(dynamic val) { ... }
}
ClassB extends BaseClass {
static ClassB? tryFrom(dynamic val) { ... }
}
...
ClassZ extends BaseClass {
static ClassZ? tryFrom(dynamic val) { ... }
}
BaseClass parser(dynamic val) {
BaseClass object = ClassA.tryFrom(val) ??
ClassB.tryFrom(val) ??
... ??
ClassZ.tryFrom(val);
if (object == null) {
// Throw some exception here.
}
return object;
}
from there, you can make parser use a loop:
typedef TryFromFunction = BaseClass? Function(dynamic);
final tryFromFunctions = [
ClassA.tryFrom,
ClassB.tryFrom,
...
ClassZ.tryFrom,
];
BaseClass parser(dynamic val) {
for (var tryFrom in tryFromFunctions) {
var object = tryFrom(val);
if (object != null) {
return object;
}
}
// Throw some exception here.
}
That wouldn't absolve you of the responsibility of updating some other location whenever a new class is added, but:
The work would be minimal.
You maybe could add unit tests to check that the list is updated. For example, if each of ClassA, ClassB, ..., ClassZ is in a separate file easily distinguished by path or filename, then you could have a test that verifies that tryFromFunctions.length matches the number of those files.
For now, I've used a solution that takes from the others listed and adds a twist. Basically, I create a list of matchers like the others but do the work of adding the matcher in the class itself. Basically,
List<BaseClass Function(dynamic)> _matchers = [];
bool addMatcher(bool Function(dynamic) matcher, BaseClass Function(dynamic) factory) {
_matchers.add((val) {
return matcher(val) ? factory(val) : null;
});
return true;
}
class ClassA extends BaseClass {
static final _ = addMatcher(matches, (val) => ClassA(val));
ClassA(val) { ... }
static bool matches(val) { ... }
}
class ClassB extends BaseClass {
static final _ = addMatcher(...);
...
}
...
BaseClass parser(val) {
for (var matcher in _matchers) {
var object = matcher(val);
if (object != null) {
return object;
}
}
// Throw some exception here.
}
The rational behind this is that I can easily verify that the class is being checked. Unfortunately I'm still not sure how to do this automatically since this was just a quick and dirty solution. I may come back to this with an update if I end up implementing source generation or unit tests for automatic generation/verification.

defining a generic class with parametrized type that expects more than one abstract class implementation in dart

interfaces
abstract class Adder<T> {
T add(T a, T b);
}
abstract class Multiplier<T> {
T multiply(T a, T b);
}
abstract class Displayer<T> {
void display(T a);
}
An implementation that just happens to implement all three.
class IntImpl implements Adder<int>, Multiplier<int>, Displayer<int> {
#override
int add(int a, int b) {
return a + b;
}
#override
int multiply(int a, int b) {
return a * b;
}
#override
void display(int a) {
print('printing: ${a}');
}
}
A consumer that needs support for two of the interfaces.
But, I could not find how to declare such a thing.
class DisplayingAdder<T, K extends Adder<T>> {
final K engine;
DisplayingAdder(this.engine);
T addAndDisplay(T a, T b) {
final r = engine.add(a, b);
// How do I change DisplayingAdder class parametrization to make the next line functional?
// engine.display(r);
return r;
}
}
Code to exercise the above
void main() {
final e1 = IntImpl();
final da = DisplayingAdder(e1);
da.addAndDisplay(3,4);
}
Not sure what can be changed to allow the generic parameter to declare support for more than one abstract class.
You can't restrict a generic type to a type that implements multiple supertypes. The best you're going to have to do is separate engine into an object that implements Adder and an object that implements Displayer, then pass the instance of IntImpl to both. (This is more scalable anyway since it also allows you to pass different values to each if you wanted.)
class DisplayingAdder<T, A extends Adder<T>, D extends Displayer<T>> {
final A adder;
final D displayer;
DisplayingAdder(this.adder, this.displayer);
T addAndDisplay(T a, T b) {
final r = adder.add(a, b);
displayer.display(r);
return r;
}
}
void main() {
final e1 = IntImpl();
final da = DisplayingAdder(e1, e1);
da.addAndDisplay(3,4);
}

Dependency Injection of Primitive Types (Decided at Runtime) With HK2

So basically, I have a situation where I want to inject primitive types into a class (i.e. a String and an Integer). You can think of a URL and port number for an application as example inputs. I have three components:
Now say I have a class, which does take in these params:
public class PrimitiveParamsDIExample {
private String a;
private Integer b;
public PrimitiveParamsDIExample(String a, Integer b) {
this.a = a;
this.b = b;
}
}
So my question here is simple. How do I inject a and b into class PrimitiveParamsDIExample?
In general, this is also asking how to inject parameters that are decided on runtime as well. If I have a and b above, read from STDIN or from an input file, they're obviously going to be different from run to run.
All the more, how do I do the above within the HK2 framework?
EDIT[02/23/15]: #jwells131313, I tried your idea, but I'm getting the following error (this one for the String param; similar one for int):
org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=String,parent=PrimitiveParamsDIExample,qualifiers
I set up classes exactly as you did in your answer. I also overrode the toString() method to print both variables a and b in PrimitiveParamsDIExample. Then, I added the following in my Hk2Module class:
public class Hk2Module extends AbstractBinder {
private Properties properties;
public Hk2Module(Properties properties){
this.properties = properties;
}
#Override
protected void configure() {
bindFactory(StringAFactory.class).to(String.class).in(RequestScoped.class);
bindFactory(IntegerBFactory.class).to(Integer.class).in(RequestScoped.class);
bind(PrimitiveParamsDIExample.class).to(PrimitiveParamsDIExample.class).in(Singleton.class);
}
}
So now, I created a test class as follows:
#RunWith(JUnit4.class)
public class TestPrimitiveParamsDIExample extends Hk2Setup {
private PrimitiveParamsDIExample example;
#Before
public void setup() throws IOException {
super.setupHk2();
//example = new PrimitiveParamsDIExample();
example = serviceLocator.getService(PrimitiveParamsDIExample.class);
}
#Test
public void testPrimitiveParamsDI() {
System.out.println(example.toString());
}
}
where, Hk2Setup is as follows:
public class Hk2Setup extends TestCase{
// the name of the resource containing the default configuration properties
private static final String DEFAULT_PROPERTIES = "defaults.properties";
protected Properties config = null;
protected ServiceLocator serviceLocator;
public void setupHk2() throws IOException{
config = new Properties();
Reader defaults = Resources.asCharSource(Resources.getResource(DEFAULT_PROPERTIES), Charsets.UTF_8).openBufferedStream();
load(config, defaults);
ApplicationHandler handler = new ApplicationHandler(new MyMainApplication(config));
final ServiceLocator locator = handler.getServiceLocator();
serviceLocator = locator;
}
private static void load(Properties p, Reader r) throws IOException {
try {
p.load(r);
} finally {
Closeables.close(r, false);
}
}
}
So somewhere, the wiring is messed up for me to get an UnsatisfiedDependencyException. What have I not correctly wired up?
Thanks!
There are two ways to do this, but one isn't documented yet (though it is available... I guess I need to work on documentation again...)
I'll go through the first way here.
Basically, you can use the HK2 Factory.
Generally when you start producing Strings and ints and long and scalars like this you qualify them, so lets start with two qualifiers:
#Retention(RUNTIME)
#Target( { TYPE, METHOD, FIELD, PARAMETER })
#javax.inject.Qualifier
public #interface A {}
and
#Retention(RUNTIME)
#Target( { TYPE, METHOD, FIELD, PARAMETER })
#javax.inject.Qualifier
public #interface B {}
then write your factories:
#Singleton // or whatever scope you want
public class StringAFactory implements Factory<String> {
#PerLookup // or whatever scope, maybe this checks the timestamp?
#A // Your qualifier
public String provide() {
// Write your code to get your value...
return whatever;
}
public void dispose(String instance) {
// Probably do nothing...
}
}
and for the Integer:
#Singleton // or whatever scope you want
public class IntegerBFactory implements Factory<Integer> {
#PerLookup // or whatever scope, maybe this checks the timestamp?
#B // Your qualifier
public Integer provide() {
// Write your code to get your value...
return whatever;
}
public void dispose(String instance) {
// Probably do nothing...
}
}
Now lets re-do your original class to accept these values:
public class PrimitiveParamsDIExample {
private String a;
private int b;
#Inject
public PrimitiveParamsDIExample(#A String a, #B int b) {
this.a = a;
this.b = b;
}
}
Note I changed Integer to int, well... just because I can. You can also just use field injection or method injection in the same way. Here is field injection, method injection is an exercise for the reader:
public class PrimitiveParamsDIExample {
#Inject #A
private String a;
#Inject #B
private int b;
public PrimitiveParamsDIExample() {
}
}
There are several ways to bind factories.
In a binder: bindFactory
Using automatic class analysis: addClasses
An EDSL outside a binder: buildFactory

Creating an instance of a generic type in DART

I was wondering if is possible to create an instance of a generic type in Dart. In other languages like Java you could work around this using reflection, but I'm not sure if this is possible in Dart.
I have this class:
class GenericController <T extends RequestHandler> {
void processRequest() {
T t = new T(); // ERROR
}
}
I tried mezonis approach with the Activator and it works. But it is an expensive approach as it uses mirrors, which requires you to use "mirrorsUsed" if you don't want to have a 2-4MB js file.
This morning I had the idea to use a generic typedef as generator and thus get rid of reflection:
You define a method type like this: (Add params if necessary)
typedef S ItemCreator<S>();
or even better:
typedef ItemCreator<S> = S Function();
Then in the class that needs to create the new instances:
class PagedListData<T>{
...
ItemCreator<T> creator;
PagedListData(ItemCreator<T> this.creator) {
}
void performMagic() {
T item = creator();
...
}
}
Then you can instantiate the PagedList like this:
PagedListData<UserListItem> users
= new PagedListData<UserListItem>(()=> new UserListItem());
You don't lose the advantage of using generic because at declaration time you need to provide the target class anyway, so defining the creator method doesn't hurt.
You can use similar code:
import "dart:mirrors";
void main() {
var controller = new GenericController<Foo>();
controller.processRequest();
}
class GenericController<T extends RequestHandler> {
void processRequest() {
//T t = new T();
T t = Activator.createInstance(T);
t.tellAboutHimself();
}
}
class Foo extends RequestHandler {
void tellAboutHimself() {
print("Hello, I am 'Foo'");
}
}
abstract class RequestHandler {
void tellAboutHimself();
}
class Activator {
static createInstance(Type type, [Symbol constructor, List
arguments, Map<Symbol, dynamic> namedArguments]) {
if (type == null) {
throw new ArgumentError("type: $type");
}
if (constructor == null) {
constructor = const Symbol("");
}
if (arguments == null) {
arguments = const [];
}
var typeMirror = reflectType(type);
if (typeMirror is ClassMirror) {
return typeMirror.newInstance(constructor, arguments,
namedArguments).reflectee;
} else {
throw new ArgumentError("Cannot create the instance of the type '$type'.");
}
}
}
I don't know if this is still useful to anyone. But I have found an easy workaround. In the function you want to initialize the type T, pass an extra argument of type T Function(). This function should return an instance of T. Now whenever you want to create object of T, call the function.
class foo<T> {
void foo(T Function() creator) {
final t = creator();
// use t
}
}
P.S. inspired by Patrick's answer
2022 answer
Just came across this problem and found out that although instantiating using T() is still not possible, you can get the constructor of an object easier with SomeClass.new in dart>=2.15.
So what you could do is:
class MyClass<T> {
final T Function() creator;
MyClass(this.creator);
T getGenericInstance() {
return creator();
}
}
and when using it:
final myClass = MyClass<SomeOtherClass>(SomeOtherClass.new)
Nothing different but looks cleaner imo.
Here's my work around for this sad limitation
class RequestHandler {
static final _constructors = {
RequestHandler: () => RequestHandler(),
RequestHandler2: () => RequestHandler2(),
};
static RequestHandler create(Type type) {
return _constructors[type]();
}
}
class RequestHandler2 extends RequestHandler {}
class GenericController<T extends RequestHandler> {
void processRequest() {
//T t = new T(); // ERROR
T t = RequestHandler.create(T);
}
}
test() {
final controller = GenericController<RequestHandler2>();
controller.processRequest();
}
Sorry but as far as I know, a type parameter cannot be used to name a constructor in an instance creation expression in Dart.
Working with FLutter
typedef S ItemCreator<S>();
mixin SharedExtension<T> {
T getSPData(ItemCreator<T> creator) async {
return creator();
}
}
Abc a = sharedObj.getSPData(()=> Abc());
P.S. inspired by Patrick
simple like that.
import 'dart:mirrors';
void main(List<String> args) {
final a = A<B>();
final b1 = a.getInstance();
final b2 = a.getInstance();
print('${b1.value}|${b1.text}|${b1.hashCode}');
print('${b2.value}|${b2.text}|${b2.hashCode}');
}
class A<T extends B> {
static int count = 0;
T getInstance() {
return reflectClass(T).newInstance(
Symbol(''),
['Text ${++count}'],
{Symbol('value'): count},
).reflectee;
}
}
class B {
final int value;
final String text;
B(this.text, {required this.value});
}
Inspired by Patrick's answer, this is the factory I ended up with.
class ServiceFactory<T> {
static final Map<Type, dynamic> _cache = <String, dynamic>{};
static T getInstance<T>(T Function() creator) {
String typeName = T.toString();
return _cache.putIfAbsent(typeName, () => creator());
}
}
Then I would use it like this.
final authClient = ServiceFactory.getInstance<AuthenticationClient>(() => AuthenticationClient());
Warning: Erik made a very good point in the comment below that the same type name can exist in multiple packages and that will cause issues. As much as I dislike to force the user to pass in a string key (that way it's the consumer's responsibility to ensuring the uniqueness of the type name), that might be the only way.

How do I extend a List in Dart?

I want to create a more specialized list in dart. I can't directly extend List. What are my options?
To make a class implement List there are several ways :
Extending ListBase and implementing length, operator[], operator[]= and length= :
import 'dart:collection';
class MyCustomList<E> extends ListBase<E> {
final List<E> l = [];
MyCustomList();
void set length(int newLength) { l.length = newLength; }
int get length => l.length;
E operator [](int index) => l[index];
void operator []=(int index, E value) { l[index] = value; }
// your custom methods
}
Mixin ListMixin and implementing length, operator[], operator[]= and length= :
import 'dart:collection';
class MyCustomList<E> extends Base with ListMixin<E> {
final List<E> l = [];
MyCustomList();
void set length(int newLength) { l.length = newLength; }
int get length => l.length;
E operator [](int index) => l[index];
void operator []=(int index, E value) { l[index] = value; }
// your custom methods
}
Delegating to an other List with DelegatingList from the quiver package:
import 'package:quiver/collection.dart';
class MyCustomList<E> extends DelegatingList<E> {
final List<E> _l = [];
List<E> get delegate => _l;
// your custom methods
}
Delegating to an other List with DelegatingList from the collection package:
import 'package:collection/wrappers.dart';
class MyCustomList<E> extends DelegatingList<E> {
final List<E> _l;
MyCustomList() : this._(<E>[]);
MyCustomList._(l) :
_l = l,
super(l);
// your custom methods
}
Depending on your code each of those options has their advantages. If you wrap/delegate an existing list you should use the last option. Otherwise, use one of the two first options depending on your type hierarchy (mixin allowing to extend another Object).
There is a ListBase class in dart:collection. If you extend this class, you only need to implement:
get length
set length
[]=
[]
Here is an example:
import 'dart:collection';
class FancyList<E> extends ListBase<E> {
List innerList = new List();
int get length => innerList.length;
void set length(int length) {
innerList.length = length;
}
void operator[]=(int index, E value) {
innerList[index] = value;
}
E operator [](int index) => innerList[index];
// Though not strictly necessary, for performance reasons
// you should implement add and addAll.
void add(E value) => innerList.add(value);
void addAll(Iterable<E> all) => innerList.addAll(all);
}
void main() {
var list = new FancyList();
list.addAll([1,2,3]);
print(list.length);
}
A new way of extending classes was introduced with Dart 2.6.
You can now create an extension of List like this:
extension MyCustomList<T> on List<T> {
// Any methods you want can be added here.
}
The methods you add can be used implicitly, i.e. you can just use them on any List when you have your extension imported.
Here is an example from the feature specification:
extension MyFancyList<T> on List<T> {
int get doubleLength => this.length * 2;
List<T> operator-() => this.reversed.toList();
List<List<T>> split(int at) =>
<List<T>>[this.sublist(0, at), this.sublist(at)];
List<T> mapToList<R>(R Function(T) convert) => this.map(convert).toList();
}
You can use these new members on any List, e.g. like this:
const list = <String>['some', 'elements'];
list.doubleLength; // Evaluates to 4.
The answers to this are pretty outdated, and I'm in the process of doing this for my own project, so I thought I'd help some people out by posting a really clean answer that doesn't involve any overriding or implementing of things.
The quiver package has an extendable List class called DelegatingList that makes extending a list trivial.
class FruitList extends DelegatingList<Fruit> {
final List<Fruit> _fruits = [];
List<Fruit> get delegate => _fruits;
// custom methods
}
Hopefully this helps someone who comes across this question like I did!
Following on from the answer above, you can create an immutable list like this:
class ImmutableList<E> extends ListBase<E> {
late final List<E> innerList;
ImmutableList(Iterable<E> items) {
innerList = List<E>.unmodifiable(items);
}
#override
int get length => innerList.length;
#override
set length(int length) {
innerList.length = length;
}
#override
void operator []=(int index, E value) {
innerList[index] = value;
}
#override
E operator [](int index) => innerList[index];
}
//list is your given List and iterable is any object in dart that can be iterated
list.addAll(Iterable)

Resources