kt_dart는 Kotlin의 표준 라이브러리의 Dart 버전으로, Dart 및 Flutter 프로젝트에 Kotlin과 유사한 컬렉션(KtList, KtMap, KtSet)과 150개 이상의 확장 메서드를 제공합니다. 리스트, 맵, 세트 연산을 위한 간결하고 표현력 있는 구문을 통해 함수형 프로그래밍 기능을 강화합니다. 이 패키지는 Android, iOS, Web, macOS, Windows, Linux 등 모든 주요 플랫폼을 지원하여 크로스플랫폼 개발에 적합합니다. Kotlin의 풍부한 컬렉션 API를 모방함으로써 코드의 가독성을 향상시키고 반복적인 코드를 줄이는 것을 목표로 합니다.
사용 사례
Dart의 함수형 프로그래밍
컬렉션 변환 간소화
Kotlin 스타일의 Dart 코드 작성
크로스플랫폼 앱 개발
데이터 조작에서 반복 코드 줄이기
코드 가독성 향상
주요 기능
150개 이상의 컬렉션 확장 메서드
Kotlin 스타일의 KtList, KtMap, KtSet
크로스 플랫폼 지원
유려하고 표현력 있는 문법
최소 종속성
Flutter와의 원활한 통합
적합한 대상
Kotlin에 익숙한 Dart 개발자
기능형 프로그래밍에 중점을 두는 프로젝트
더 깨끗한 수집 처리를 원하는 팀
강력한 데이터 작업을 필요로 하는 플러터 앱
Dart에서 코틀린과 유사한 구문을 원하는 개발자
고려 사항
신규 사용자를 위한 학습 곡선
추상화로 인한 잠재적인 성능 오버헤드
완전한 코틀린 대체품이 아님
Kotlin에 비해 문서가 제한적
패키지 크기가 약간 증가할 수 있습니다
대규모 코드베이스에서는 주의 깊은 마이그레이션이 필요합니다
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
kt.dart
This project is a port of Kotlin's Kotlin Standard library for Dart/Flutter projects. It's a useful addition to dart:core and includes collections (KtList, KtMap, KtSet) as well as other packages which can improve every Dart/Flutter app.
dependencies:kt_dart:^1.1.0
import'package:kt_dart/kt.dart';
Motivation
Dart's dart:core package provides basic building blocks. But sometimes they are too low level and not as straightforward as Kotlin's kotlin-stdlib.
Here are a few examples of what this project offers: (click to expand)
Immutable collections by default
dart:core collections
Dart's List is mutable by default. The immutable List.unmodifiable is the same type, but the mutation methods throw at runtime.
final dartList = [1, 2, 3];
dartList.add(4); // mutation is by default possibleassert(dartList.length == 4);
final immutableDartList = List.unmodifiable(dartList);
immutableDartList.add(5); // throws: Unsupported operation: Cannot add to an unmodifiable list
Dart's mutable List is indistinguishable from an immutable List which might cause errors.
voidaddDevice(List<Widget> widgets, Device device) {
// no way to check whether widgets is mutable or not// add might or might now throw
widgets.add(_deviceRow());
widgets.add(Divider(height: 1.0));
}
kt_dart collections
KtList and KtMutableList are two different Types. KtList is immutable by default and has no mutation methods (such as add). Methods like map((T)->R) or plusElement(T) return a new KtList leaving the old one unmodified.
final ktList = listOf(1, 2, 3);
// The method 'add' isn't defined for the class 'KtList<int>'.
ktList.add(4); // compilation error
^^^
// Adding an item returns a new KtListfinal mutatedList = ktList.plusElement(4);
assert(ktList.size == 3);
assert(mutatedList.size == 4);
KtMutableList offers mutation methods where the content of that collection can be actually mutated.
I.e. with remove(T) or add(T);
Dart's List works like a Array in Java. Equals doesn't compare the items; it only checks the identity.
To compare the contents you have to use helper methods methods from 'package:collection/collection.dart'.
// Comparing two Dart Lists works only by identityfinal a = [1, 2, 3, 4];
final b = [1, 2, 3, 4];
print(a == b); // false, huh?// Content-based comparisons require unnecessary glue codeFunction listEq = constListEquality().equals;
print(listEq(a, b)); // true// MapEquality isn't deep by defaultfinal x = {1: ["a", "b", "c"], 2: ["xx", "yy", "zz"]};
final y = {1: ["a", "b", "c"], 2: ["xx", "yy", "zz"]};
Function mapEq = constMapEquality().equals;
print(mapEq(x, y)); // false, wtf?!Function deepEq = constDeepCollectionEquality().equals;
print(deepEq(x, y)); // true, finally
kt_dart collections
KtList and all other collection types implement equals by deeply comparing all items.
final a = listOf(1, 2, 3, 4);
final b = listOf(1, 2, 3, 4);
print(a == b); // true, as expectedfinal x = mapFrom({1: listOf("a", "b", "c"), 2: listOf("xx", "yy", "zz")});
final y = mapFrom({1: listOf("a", "b", "c"), 2: listOf("xx", "yy", "zz")});
print(x == y); // deep equals by default
Common methods
Some of Dart's method names feel unfamiliar. That's because modern languages and frameworks (Kotlin, Swift, TypeScript, ReactiveExtensions) kind of agreed on naming methods when it comes to collections. This makes it easy to switch platforms and discuss implementations with coworkers working with a different language.
kt_dart does not ship extension methods on dart:core types such as String or int. It focuses on Kotlin-style collections, conversions to and from those types, and a few generic helpers on T in standard.dart (let, also, takeIf, …).
For String, int, Duration, and similar, use dartx. It is fully compatible with kt_dart — there are no naming clashes. Methods such as toIntOrNull and toDoubleOrNull already live there.
KtList
KtList is a read-only list of elements. It is immutable because it doesn't offer mutation methods such as remove or add.
Use KtMutableMap if you want to use a mutable list.
To create a KtList/KtMutableList use the KtList.of constructor or convert an existing Dart List to a KtList with the list.toImmutableList() extension.
Create a KtList
// Create a KtList from scratchfinal beatles = KtList.of("John", "Paul", "George", "Ringo");
// Convert a existing List to KtListfinal abba = ["Agnetha", "Björn", "Benny", "Anni-Frid"];
final immutableAbba = abba.toImmutableList();
Create a KtMutableList
KtList is immutable by default, which means it doesn't offer methods like add or remove.
To create mutable list with kt_dart use the KtMutableList constructor.
// Create a KtMutableList from scratchfinal beatles = KtMutableList.of("John", "Paul", "George", "Ringo");
beatles.removeAt(0);
print(beatles); // [Paul, George, Ringo]
Mutable/Immutable conversion
Conversions between KtList and KtMutableList can be done with KtList.toMutableList() and KtMutableList.toList();
kt_dart collections do not implement Iterable.
It is therefore not possible to directly iterate over the entries of a KtList.
All kt_dart collections offer a .iter property which exposes a Dart Iterable.
For-loops therefore don't look much different.
final beatles = KtList.of("John", "Paul", "George", "Ringo");
for (final member in beatles.iter) {
print(member);
}
Yes, alternatively you could use .asList() instead which returns a Dart List.
Kotlin syntax
Kotlin users might be more familiar with the listOf() and mutableListOf() functions.
Use them if you like but keep in mind that the dart community is much more used to use constructors instead of top-level functions.
final beatles = listOf("John", "Paul", "George", "Ringo");
final abba = mutableListOf("Agnetha", "Björn", "Benny", "Anni-Frid");
KtSet
A KtSet is a unordered collection of elements without duplicates.
Creating a KtSet/KtMutableSet is very similar to the KtList API.
// Create a KtSet from scratchfinal beatles = KtSet.of("John", "Paul", "George", "Ringo");
// Convert a existing Set to KtSetfinal abba = {"Agnetha", "Björn", "Benny", "Anni-Frid"};
final immutableAbba = abba.toImmutableSet();
KtMap
To create a KtMap/KtMutableMap start with Dart Map and then convert it to a KtMap with either:
You may want to use a specific Map implementation. kt_dart offers:
KtLinkedMap - based on Darts LinkedHashMap where the insertion order of keys is remembered and keys are iterated in the order they were inserted into the map
KtHashMap - based on Darts HashMap where keys of a HashMap must have consistent [Object.==] and [Object.hashCode] implementations. Iterating the map's keys, values or entries (through [forEach]) may happen in any order.
KtPair, KtTriple
kt_dart offer two types of tuples, KtPair with two elements and KtTriple with three elements.
They are used by some collection APIs and prevent a 3rd party dependency.
final beatles = KtList.of("John", "Paul", "George", "Ringo");
final partitions = beatles.partition((it) => it.contains("n"));
print(partitions.first); // [John, Ringo]print(partitions.second); // [Paul, George]
There won't be a KtQuadruple or TupleN in this library.
If you want to use tuples heavily in you application consider using the tuple package.
Better, use freezed to generated data classes which makes for a much better API.
Annotations
@nullable
Kotlin already has Non-Nullable types, something which is coming to Dart soon™.
kt_dart already makes use of Non-Nullable Types and never returns null unless a method is annotated with @nullable.
There isn't any tooling which will warn you about the wrong usage but at least it's documented.
And once nnbd lands in Dart it will be fairly easy to convert.
@nonNull
This annotation annotates methods which never return null.
Although this is the default in kt_dart, is makes it very obvious for methods which sometimes return null in other languages.
@experimental
A method/class annotated with @experimental marks the method/class as experimental feature. Experimental APIs can be changed or removed at any time.
License
Copyright2019PascalWelschLicensed under the ApacheLicense, Version2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0Unlessrequired by applicable law or agreed to in writing, software
distributed under the Licenseis distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the Licensefor the specific language governing permissions and
limitations under the License.