Skip to content

Instantly share code, notes, and snippets.

View kwalrath's full-sized avatar

Kathy Walrath kwalrath

View GitHub Profile
@kwalrath
kwalrath / main.dart
Created March 11, 2021 18:37 — forked from miquelbeltran/main.dart
Java-to-Dart codelab: CircleMock example
import 'dart:math';
abstract class Shape {
factory Shape(String type) {
if (type == 'circle') return Circle(2);
if (type == 'square') return Square(2);
throw 'Can\'t create $type.';
}
num get area;
}
@kwalrath
kwalrath / montecarlo.dart
Last active March 23, 2022 01:10 — forked from timsneath/montecarlo.dart
DartPad for dart.dev/overview
import 'dart:math' show Random;
main() async {
print('Compute π using the Monte Carlo method.');
await for (final estimate in computePi().take(100)) {
print('π ≅ $estimate');
}
}
/// Generates a stream of increasingly accurate estimates of π.
@kwalrath
kwalrath / callable_function.dart
Last active April 8, 2020 23:50 — forked from Sfshaza/callable_function.dart
Callable object
class WannabeFunction {
String call(String a, String b, String c) => '$a $b $c!';
}
var wf = WannabeFunction();
var out = wf('Hi', 'there,', 'gang');
main() => print(out);
// Add a contravariant variance modifier
class Writer<in T> {
void write(T x) => print(x);
}
main() {
// Error! Cannot assign Writer<int> to Writer<Object> because the type
// parameter is contravariantly declared.
Writer<Object> objectWriter = new Writer<int>();
}
void main() {
var iterable = ['Salad', 'Popcorn', 'Toast'];
for (var element in iterable) {
print(element);
}
}
void main() {
Iterable iterable = ['Salad', 'Popcorn', 'Toast'];
print('The first element is ${iterable.first}');
print('The last element is ${iterable.last}');
}
bool predicate(String element) {
return element.length > 5;
}
main() {
var items = ['Salad', 'Popcorn', 'Toast', 'Lasagne'];
// You can find with a simple expression:
var element1 = items.firstWhere((element) => element.length > 5);
print(element1);
Use the methods `contains` and `startWith` from the `String` class.
void main() {
var items = ['Salad', 'Popcorn', 'Toast'];
if (items.any((element) => element.contains('a'))) {
print('At least one element contains "a"');
}
if (items.every((element) => element.length >= 5)) {
print('All elements have length >= 5');
}
Use the methods `any` and `every` to compare the user age.