LoginSignup
2
2

More than 5 years have passed since last update.

dart:coreを旅する

Last updated at Posted at 2014-12-11

「Dart Advent Calendar 2014」 12日目は@zukkunが担当します。

今回は、少し基礎に戻ってみて、dart:coreのAPIを眺めてみます。その中で気になったものや紹介したいものをチョイスして解説していきます。

dart:coreとは

Dartの標準ライブラリの1つで、言語機能の中核となるような機能を提供します。

標準ライブラリは「dart:○○」という形の名称になっており、通常import "dart:○○;"という形で読み込む必要があるのですが、dart:coreはimportしなくても使えるものになっています。

identical関数

bool identical(Object a, Object b)

オブジェクトが同一かどうか調べます。

class Hoge {}

main() {
  Hoge hoge1 = new Hoge();
  Hoge hoge2 = new Hoge();
  Hoge hoge3 = hoge1;

  print(identical(hoge1, hoge2));
  print(identical(hoge1, hoge3));
}
結果
false
true

identityHashCode関数

int identityHashCode(Object object)

オブジェクトのハッシュ値を返します。

class Hoge {}

main() {
  Hoge hoge = new Hoge();
  print(identityHashCode(hoge));
}
結果
991528256

なんかに使えると思います。

DateTimeクラス

日時を扱います。

main() {
  print(new DateTime.now());
  print(new DateTime(2014, 12, 25));
}
結果
2014-12-12 00:22:22.797
2014-12-25 00:00:00.000

Durationクラス

時間の長さを扱います。

main() {
  DateTime christmas = new DateTime(2014, 12, 25);
  DateTime now = new DateTime.now();
  Duration difference = christmas.difference(now);

  print('クリスマスまで、あと${difference.inDays}日');
}
結果
クリスマスまで、あと12日

List< E >抽象クラス

リストを扱います。

main() {
  List<int> list = new List<int>.generate(10, (index) => index);
  List<int> even = list.where((value) => value % 2 == 0).toList();
  print(list);
  print(even);
}
結果
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8]

リテラルとして[1, 2, 3]と書くと、Listオブジェクトとして扱えます。

Stopwatchクラス

時間を測ることができます。

main() {
  Stopwatch stopwatch = new Stopwatch()..start();
  stopwatch.stop();
  Duration elapsed = stopwatch.elapsed;
  print(elapsed.inMicroseconds); // stopwatch.elapsedMicrosecondsでも良い
}
結果
455

Stringクラス

文字列を扱います。

main() {
  // "○○"はStringオブジェクトとして扱える
  // Stringクラスの*演算子を使用
  print("hoge" * 5);
}
結果
hogehogehogehogehoge

まとめ

他にも色々な機能や、紹介したクラスでも紹介していない様々なメソッドがあります。

これからも酒のつまみにリファレンスのぶらり旅をしていこうと思います。

明日は@ntaooさんです!

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2