Integrate other languages (like Java and Kotlin) code style to extensions.
Dart Class | Java Class | Dart Prototype |
---|---|---|
Consumer<T> | Consumer<T> | void Function(T) |
Predicate<T> | Predicate<T> | bool Function(T) |
Action | Action | void Function() |
Supplier<R> | Supplier<R> | R Function() |
Transformer<T, R> | Function<T, R> | R Function(T) |
BiConsumer<T, U> | BiConsumer<T, U> | void Function(T, U) |
BiPredicate<T, U> | BiPredicate<T, U> | bool Function(T, U) |
BiTransformer<T, U, R> | BiFunction<T, U, R> | R Function(T, U) |
Operator | Parameter | Returns |
---|---|---|
let | self | self |
apply | - | self |
also | self | R |
run | - | R |
String name = null;
name?.let((it){
print("it=$it");
});
Because
name
is null, solet
not execute.
String name = "Hello";
name?.let((it){
print("it=$it");
});
Because
name
is not null, so outputs "it=Hello".
By cascade style
People john = People()
..name = "John"
..age = 18;
By let
operator
People john = People().let((it) {
it.name = "John";
it.age = 18;
});
100.also((it) => it * it)
.also((it) => it.toString())
.also((it) => double.parse(it))
.let((it) => print("result=$it"));
You can call invoke
to execute a Function
.
Function func = () => print("Execute");
func();
Function func = () => print("Execute");
func.invoke();
Dart style Function
null safety
Function func = null;
if(func != null) func();
Instead of invoke
and let
style
Function func = null;
func?.invoke();
Parameters and returns will auto transform and keep type-safe.
typedef Func1 = bool Function(String s, int i);
typedef Func2 = String Function(int i);
Func1 func1 = null;
bool result1 = func1?.invoke("String", 100);
Func2 func2 = null;
String result2 = func2?.invoke(100);
func2?.invoke(true); /// compile error
bool r = func2?.invoke(100); /// compile errpr
Property | Type | R/W |
---|---|---|
lastIndex | int | R |
Return Type | Method |
---|---|
Iterable<IndexedValue> | withIndex() |
Iterable<E> | whereNot(bool test(E element)) |
Iterable<int> | indexes() |
E | elementAtOr(int index, [E defaultValue = null]) |
E | firstOr([E defaultValue = null]) |
E | lastOr([E defaultValue = null]) |
Use cast
instead of as
to make chain style.
dynamic o = "Hello";
(o as String).length;
o.cast<String>().length;
((o as String) as String).length;
o.cast<String>().cast<String>().length;