Skip to content

Instantly share code, notes, and snippets.

@davidmigloz
Last active April 20, 2021 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidmigloz/ecd39257ea642dc30433666e6a8d32c0 to your computer and use it in GitHub Desktop.
Save davidmigloz/ecd39257ea642dc30433666e6a8d32c0 to your computer and use it in GitHub Desktop.
Dart vs Kotlin: type check and cast operators
import 'package:collection/collection.dart';
void main() {
Iterable iterable1 = [1, 2, 3];
Iterable iterable2 = {1, 2, 3};
if (iterable1 is List && iterable2 is List) {
iterable1.shuffle(); // Smart cast from Iterable to List
print(ListEquality().equals(iterable1, iterable2));
} else {
print(IterableEquality().equals(iterable1, iterable2));
}
if (iterable1 is! List) {
throw ArgumentError("A list is required");
}
final list = iterable1;
final set = iterable2 as Set; // Explicit cast
}
fun main() {
var iterable1: Iterable<Int> = mutableListOf(1, 2, 3)
var iterable2: Iterable<Int> = setOf(1, 2, 3)
if (iterable1 is MutableList && iterable2 is List) {
iterable1.shuffle() // Smart cast from Iterable to MutableList
print(iterable1 == iterable2)
} else {
print(iterable1 == iterable2)
}
if (iterable1 !is List) {
error("A list is required")
}
val list = iterable1
val set = iterable2 as Set // Explicit cast
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment