-
-
Notifications
You must be signed in to change notification settings - Fork 30
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
KList should support const constructor #62
Comments
kt.dart can't offer const constructors because import 'package:dart_kollection/src/util/hash.dart';
import 'package:test/test.dart';
class MyList<T> {
const MyList.from(List<T> list) : _list = list;
// doesn't compile because T is not necessarily const
// error: The values in a const list literal must be constants. (non_constant_list_element at [dart_kollection] test/const_list_test.dart:8)
//const MyList.of(T arg1, T arg2, T arg3) : _list = const [arg1, arg2, arg3];
// List doesn't offer a const constructor to copy the list and make MyList immutable
// error: Initializer expressions in constant constructors must be constants. (non_constant_value_in_initializer at [dart_kollection] test/const_list_test.dart:11)
//const MyList.copy(List<T> list): _list = List.from(list);
final List<T> _list;
bool contains(T element) {
return _list.contains(element);
}
@override
int get hashCode {
return 1 + hashObjects(_list);
}
@override
bool operator ==(dynamic other) {
if (identical(other, this)) return true;
if (other is! MyList) return false;
if (other._list.length != _list.length) return false;
if (other.hashCode != hashCode) return false;
for (var i = 0; i != _list.length; ++i) {
if (other._list[i] != _list[i]) return false;
}
return true;
}
}
void main() {
// Great!
test("const MyList are identical and equal", () {
final a = const MyList.from(["a", "b", "c"]);
final b = const MyList.from(["a", "b", "c"]);
expect(identical(a, b), isTrue);
expect(a == b, isTrue);
});
// That's fine
test("MyList are equal but not identical", () {
final a = MyList.from(["a", "b", "c"]);
final b = MyList.from(["a", "b", "c"]);
expect(identical(a, b), isFalse);
expect(a == b, isTrue);
});
// That's odd
test("MyList can be mutated!", () {
final list = ["a", "b", "c"];
final a = MyList.from(list);
final b = MyList.from(["a", "b", "c"]);
expect(a == b, isTrue);
// mutation is possible although MyList tries to be immutable.
list.add("d");
expect(a == b, isTrue);
});
}
Two major issues exist.
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With a const constructor
KList
could be created at compile time. Const constructors should be preferred whenever possible.The text was updated successfully, but these errors were encountered: