2022/5/24/Dart/Intro to Dart for Java Developersの訳

 

Contents

Intro to Dart for Java Developers

1. Introduction

Dart is the programming language for Flutter, Google’s UI toolkit for building beautiful, natively compiled mobile, web, and desktop apps from a single codebase.

Dartは、単一のコードベースから美しいネイティブコンパイルのモバイル、ウェブ、デスクトップアプリケーションを構築するためのGoogleのUIツールキットであるFlutterのためのプログラミング言語です。

 

This codelab introduces you to Dart with a focus on features that Java developers might not expect. You can write Dart functions in 1 minute, scripts in 5 minutes, and apps in 10 minutes!

このコードラボでは、Java開発者が思いもよらないような機能に焦点を当てて、Dartを紹介します。1分でDartの関数、5分でスクリプト、10分でアプリが書けるようになります!

 

What you’ll learn

  • How to create constructors

コンストラクタ

  • Different ways to specify parameters

引数

  • When and how to create getters and setters

ゲッタ、セッタの使い方

  • How Dart handles privacy

アクセス制御

  • How to create factories

ファクトリ

  • How functional programming works in Dart

関数プログラミングがDartでどう機能するか

  • Other core Dart concepts

その他のDartのコンセプト

What you’ll need

To complete this codelab, all you need is a browser!

ブラウザのみでこのコードラボを完了することができます。

You’ll write and run all the examples in DartPad, an interactive, browser-based tool that lets you play with Dart language features and core libraries. If you prefer, you can use an IDE instead, such as WebStorm, IntelliJ with the Dart plugin, or Visual Studio Code with the Dart Code extension.

DartPad は、Dart 言語機能やコアライブラリを操作できるブラウザベースの対話型ツールで、すべてのサンプルを作成し、実行します。ご希望であれば、WebStorm、Dartプラグインを備えたIntelliJ、Dart Code拡張機能を備えたVisual Studio CodeなどのIDEを代わりに使用することができます。


2. Create a simple Dart class

You’ll start by building a simple Dart class with the same functionality as the Bicycle class from the Java Tutorial. The Bicycle class contains some private instance variables with getters and setters. A main() method instantiates a Bicycle and prints it to the console.

まず、Java チュートリアルの Bicycle クラスと同じ機能を持つ簡単な Dart クラスを作成します。Bicycleクラスには、ゲッターとセッターを持ついくつかのプライベートなインスタンス変数が含まれています。main() メソッドは Bicycle をインスタンス化し、コンソールに表示します。

 

Launch DartPad

This codelab provides a new DartPad instance for every set of exercises. The link below opens a fresh instance, which contains a default “Hello” example. You can continue to use the same DartPad throughout the codelab, but if you click Reset, DartPad takes you back to the default example, losing your work.

このコードラボでは、練習問題ごとに新しいDartPadインスタンスを提供します。以下のリンクから新しいインスタンスが開き、デフォルトの「Hello」の例が含まれています。このコードラボでは、同じDartPadを使い続けることができますが、リセットをクリックすると、DartPadはデフォルトの例題に戻り、あなたの作業は失われます。

Note: For your convenience, at the top of each codelab page is a DartPad instance that reflects the state at the beginning of each exercise.

注:便宜上、各コードラブのページの上部には、各エクササイズの開始時の状態を反映したDartPadのインスタンスが表示されています。

Open DartPad


Define a Bicycle class

Above the main() function, add a Bicycle class with three instance variables. Also remove the contents from main(), as shown in the following code snippet:

main()関数の上に、3つのインスタンス変数を持つBicycleクラスを定義します。さらに下記のコードスニペットのように、main()関数の中身を消します。

class Bicycle {
  int cadence;
  int speed;
  int gear;
}

void main() {
}

cf1e10b838bf60ee.png Observations

  • With this example, the Dart analyzer produces an error informing you that the variables must be initialized because they’re non-nullable. You’ll fix that in the next section.

この例では、Dart アナライザーは、「変数がnon-nullable型なので初期化する必要があること」を通知するエラーを生成します。これは次のセクションで修正します。

int gear;

と宣言した時のint型はnon-nullable型。この場合変数gearの値がnullになることはありません。

int? gear;

と宣言した時のint?型はnullable型。この場合変数gearの値がnullになる可能性があります。

  • Dart’s main method is named main(). If you need access to command-line arguments, you can add them: main(List<String> args).

Dartのmain関数はmain()です。コマンドライン引数にアクセスする必要があるときは、main(List<String> args)のようにすることができます。

  • The main() method lives at the top level. In Dart, you can define code outside of classes. Variables, functions, getters, and setters can all live outside of classes.

main()メソッドはトップレベルに存在します。Dartでは、クラスの外側でコードを定義することができます。変数、関数、ゲッター、セッターはすべてクラスの外側に置くことができます。

  • The original Java example declares private instance variables using the private tag, which Dart doesn’t use. You’ll learn more about privacy a little later, in “Add a read-only variable.”

オリジナルのJavaのサンプルではプライベート変数をprivateタグを使って宣言しています。一方Dartではprivateタグを使いません。少し後でアクセス制御(読み取り専用変数)について学びます。

  • Neither main() nor Bicycle is declared as public, because all identifiers are public by default. Dart doesn’t have keywords for public, private, or protected.

main()メソッドもBicycleクラスもpublicとして宣言されていません。なぜなら全ての識別子はデフォルトでpublicになります。Dartにはpublic, privateprotectedのキーワードはありません。

  • Dart uses two-character indentation by convention instead of four. You don’t need to worry about Dart’s whitespace conventions, thanks to a handy tool called dart format. As the Dart code conventions ( Effective Dart) say, “The official whitespace-handling rules for Dart are whatever dart format produces.”

Dart では、慣例的に 4 文字ではなく 2 文字のインデントが使用されています。Dartの空白の規則については、dartフォーマットという便利なツールのおかげで心配する必要はありません。Dartのコード規約(Effective Dart)には、「Dartの公式な空白処理規則は、dart formatが生成するものである」と書かれています。


Define a Bicycle constructor

Add the following constructor to the Bicycle class:

Bicycleクラスに下記のコンストラクタを追加しましょう。

Bicycle(this.cadence, this.speed, this.gear);
  • This constructor has no body, which is valid in Dart.

このコンストラクタはbodyがありません。Dartではこれは正しいコードです。

  • If you forget the semicolon (;) at the end of a no-body constructor, DartPad displays the following error: “A function body must be provided.”

no-bodyのコンストラクタの最後にセミコロン(;)を付けないと、DartPadは下記のエラーを示します。 “A function body must be provided.”

  • Using this in a constructor’s parameter list is a handy shortcut for assigning values to instance variables.

コンストラクタのパラメータリストでthisを使っています。これはインスタンス変数に値をセットする時の便利なショートカットです。

  • The code above is equivalent to the following, which uses an initializer list:

上記のコンストラクタは下記のイニシャライザリストを使用した記法と同じ意味です。

Bicycle(int cadence, int speed, int gear)
      : this.cadence = cadence,
        this.speed = speed,
        this.gear = gear;

 


Format the code

Reformat the Dart code at any time by clicking Format at the top of the DartPad UI. Reformatting is particularly useful when you paste code into DartPad and the justification is off.

DartPad UI の上部にある[フォーマット]をクリックすると、いつでも Dart コードを再フォーマットすることができます。再フォーマットは、DartPad にコードを貼り付ける際、両端揃えがずれている場合に特に便利です。


Instantiate and print a Bicycle instance

b2f84ff91b0e1396.png Add the following code to the main() function:

下記のようにをmain()関数内にコードを追加しましょう。

void main() {
  var bike = new Bicycle(2, 0, 1);
  print(bike);
}

b2f84ff91b0e1396.png Remove the optional new keyword:

newキーワードを消してみましょう。(newキーワードは無くても問題無い。)

var bike = Bicycle(2, 0, 1);

cf1e10b838bf60ee.png Observation

  • The new keyword became optional in Dart 2.

newキーワードはDart2でオプショナルになりました。

  • If you know that a variable’s value won’t change, then you can use final instead of var.

変数の値が変化しないことがわかっている場合は、varの代わりにfinalを使いましょう。

  • The print() function accepts any object (not just strings). It converts it to a String using the object’s toString() method.

print()関数はあらゆるオブジェクト(String型以外でも)受け入れます。print()関数はtoString()メソッドを利用してString型へ変換してコンソールに出力します。


Run the example

b2f84ff91b0e1396.png Execute the example by clicking Run at the top of the DartPad window. If Run isn’t enabled, see the Problems section later in this page.

DartPadウィンドウの上部にある[Run]をクリックして、サンプルを実行します。Runが有効になっていない場合は、このページの後の問題セクションを参照してください。

You should see the following output:

下記のような出力が表示されるはずです。

Instance of 'Bicycle'

cf1e10b838bf60ee.png Observation

  • No errors or warnings should appear, indicating that type inference is working, and that the analyzer infers that the statement that begins with var bike = defines a Bicycle instance.

全くエラーも警告も出ない、ということは、型推測(type inference)が機能していることを示しています。アナライザーは、var bike =で始まる文について、変数bikeの型はBicycle型(クラス)である、と推測しています。

Bicycle bike = Bicycle(2, 0, 1);

と宣言しなくても、型推測で「変数bikeの型はBicycle型」と推測される。


Improve the output

While the output “Instance of ‘Bicycle'” is correct, it’s not very informative. All Dart classes have a toString() method that you can override to provide more useful output.

“Instance of ‘Bicycle'”という出力は正しいのですが、(型情報だけでは)あまり参考になりません。すべてのDartクラスにはtoString()メソッドがあり、これをオーバーライドすればより有用な出力を得ることができます。

b2f84ff91b0e1396.png Add the following toString() method anywhere in the Bicycle class:

Bicycleクラスの定義の中に下記のtoString()メソッド(のオーバーライド)を追加してください。

@override
String toString() => 'Bicycle: $speed mph';

cf1e10b838bf60ee.png Observations

  • The @override annotation tells the analyzer that you are intentionally overriding a member. The analyzer raises an error if you fail to properly perform the override.

@overrideアノテーションは、アナライザーに対して意図的にメンバーをオーバーライドすることを示しています。

  • Dart supports single or double quotes when specifying strings.

Dartでは、String型のリテラルを記述する時、シングルクオーテーションもダブルクオーテーションも使用できます。

  • Use string interpolation to put the value of an expression inside a string literal: ${expression}. If the expression is an identifier, you can skip the braces: $variableName.

String型のリテラルの中に式の値を入れ込みたい場合は、${expression}のようにすれば可能です。式が変数(識別子)の場合中カッコは不要です。つまり$variableNameのように書けばOKです。

  • Shorten one-line functions or methods using fat arrow (=>) notation.

ボディが1行の関数は、(上記のように)アロー関数の記法が使えます。


Run the example

b2f84ff91b0e1396.png Click Run.

You should see the following output:

下記のように出力が表示されるはずです。

Bicycle: 0 mph

Problems?Check your code.

挙動が違う場合はコードをチェックしてみましょう。


Add a read-only variable

The original Java example defines speed as a read-only variable—it declares it as private and provides only a getter. Next, you’ll provide the same functionality in Dart.

オリジナルのJavaのサンプルではspeed変数が読み取り専用変数として宣言されています。プライベートでゲッターとして宣言されています。これをDartで表現してみましょう。

 

b2f84ff91b0e1396.png Open bicycle.dart in DartPad (or continue using your copy).

To mark a Dart identifier as private to its library, start its name with an underscore (_). You can convert speed to read-only by changing its name and adding a getter.

Dartの識別子(変数)をライブラリに対してプライベートにしたい場合、識別子名をアンダースコア( _ )で書き始めてください。

正確にはファイルプライベート。一つのファイル内からのみアクセス可能。一つのファイルに一つのクラス(ライブラリ)のみ定義するのであれば「クラス(ライブラリ)に対してプライベート」ということになる。

名前を変えてゲッター(getキーワード)を追加することで、speedを読み取り専用に変換することができます。

Make speed a private, read-only instance variable

b2f84ff91b0e1396.png In the Bicycle constructor, remove the speed parameter:

Bicycleクラスのコンストラクタのspeedパラメータを削除します。

Bicycle(this.cadence, this.gear);

b2f84ff91b0e1396.png In main(), remove the second (speed) parameter from the call to the Bicycle constructor:

main()関数内で、Bicycleコンストラクタの第二引数(speed)を削除します。

var bike = Bicycle(2, 1);

b2f84ff91b0e1396.png Change the remaining occurrences of speed to _speed. (Two places)

残りのspeedを_speedに修正します(2ヶ所)。

Tip: If you are using a JetBrains IDE, you can simultaneously rename all instances of a variable by right-clicking the name, and choosing Refactor > Rename from the popup menu.

JetBrains IDEを使用している場合、「右クリック > Refactor > Rename」で、変数のインスタンス全箇所の変数名を一度に修正できます。

b2f84ff91b0e1396.png Initialize _speed to 0:

_speedを0で初期化します。

int _speed = 0;

b2f84ff91b0e1396.png Add the following getter to the Bicycle class:

Bicycleクラスに下記のゲッターを追加します。

int get speed => _speed;

 

cf1e10b838bf60ee.png Observations

  • Each variable (even if it’s a number) must either be initialized or be declared nullable by adding ? to its type declaration.

全ての変数(それが数値であっても)は、(non-nullable型の場合は)初期化されるか、あるいはnullable型として型宣言されるか、どちらかが必要です。

lateキーワードを使えばnon-nullable型変数(フィールド)を初期化無しで宣言することも可能ではある。詳しくはこちら

  • The Dart compiler enforces library privacy for any identifier prefixed with an underscore. Library privacy generally means that the identifier is visible only inside the file (not just the class) that the identifier is defined in.

Dart コンパイラは、アンダースコアを先頭に持つ識別子に対して、ライブラリのプライバシーを強制します。ライブラリのプライバシーとは、一般に識別子が定義されているファイル (クラスだけではありません) の中だけで識別子が見えるようにすることを意味します。

  • By default, Dart provides implicit getters and setters for all public instance variables. You don’t need to define your own getters or setters unless you want to enforce read-only or write-only variables, compute or verify a value, or update a value elsewhere.

デフォルトでは、Dart はすべてのパブリックインスタンス変数に対して暗黙のゲッターとセッターを提供します。読み取り専用や書き込み専用の変数を強制したり、値を計算したり検証したり、 別の場所で値を更新したりするのでなければ、自分でゲッターやセッターを定義する必要はありません。

  • The original Java sample provided getters and setters for cadence and gear. The Dart sample doesn’t need explicit getters and setters for those, so it just uses instance variables.

オリジナルのJavaサンプルでは、cadenceとgearにゲッターとセッターを用意していました。Dartのサンプルでは、これらの明示的なゲッターとセッターは必要ないので、インスタンス変数を使用するだけです。

  • You might start with a simple field, such as bike.cadence, and later refactor it to use getters and setters. The API stays the same. In other words, going from a field to a getter and setter is not a breaking change in Dart.

bike.cadenceのようなシンプルなフィールドから始めて、後でゲッターとセッターを使うようにリファクタリングするかもしれません。APIは同じままです(APIにとって重大な変更にはならない)。言い換えれば、フィールドからゲッターとセッターに変更しても、Dartでは壊れるような変更(breaking change)ではありません。

b2f84ff91b0e1396.png Add the following methods to the Bicycle class:

Bicycleクラスに下記のメソッドを追加します。

void applyBrake(int decrement) {
  _speed -= decrement;
}

void speedUp(int increment) {
  _speed += increment;
}

The final Dart example looks similar to the original Java, but is more compact at 23 lines instead of 40:

DartのサンプルはオリジナルのJavaのサンプルと似ていますが、40行→23行とコンパクトになっています。

class Bicycle {
  int cadence;
  int _speed = 0;
  int get speed => _speed;
  int gear;

  Bicycle(this.cadence, this.gear);

  void applyBrake(int decrement) {
    _speed -= decrement;
  }

  void speedUp(int increment) {
    _speed += increment;
  }

  @override
  String toString() => 'Bicycle: $_speed mph';
}

void main() {
  var bike = Bicycle(2, 1);
  print(bike);
}

Problems?Check your code.


3. Use optional parameters (instead of overloading)

The next exercise defines a Rectangle class, another example from the Java Tutorial.

次のエクササイズではRectangelクラスを定義します。Javaの他のチュートリアルから作ったエクササイズです。

The Java code shows overloading constructors, a common practice in Java where constructors have the same name, but differ in the number or type of parameters. Dart doesn’t support overloading constructors and handles this situation differently, as you’ll see in this section.

Java のコードでは、コンストラクタのオーバーロードが示されています。Java では、コンストラクタは同じ名前ですが、パラメータの数または種類が異なる「overloading constructors」を使う、という一般的な慣行があります。Dart はオーバーロード コンストラクタ(overloading constructors)をサポートしておらず、このセクションで説明するように、この状況は異なる方法で処理されます。

b2f84ff91b0e1396.png Open the Rectangle example in DartPad.


Add a Rectangle constructor

b2f84ff91b0e1396.png Add a single, empty constructor that replaces all four constructors in the Java example:

Javaの四つのコンストラクタを置き換える、下記の、一つの空のコンストラクタを追加します。

Rectangle({this.origin = const Point(0, 0), this.width = 0, this.height = 0});

This constructor uses optional named parameters.

このコンストラクタではオプショナル名前付き引数(named parameters)が使用されています。

cf1e10b838bf60ee.png Observations

  • this.origin, this.width, and this.height use the shorthand trick for assigning instance variables inside a constructor’s declaration.

コンストラクタの宣言内でフィールドに値をセットするためのショートハンドトリックが使われています。

  • this.origin, this.width, and this.height are optional named parameters. Named parameters are enclosed in curly braces ({}).

origin,width,heightはオプショナル名前付き引数(optional named parameters)です。上記のように引数を中括弧( { } )で囲むとオプショナル名前付き引数になります。

  • The this.origin = const Point(0, 0) syntax specifies a default value of Point(0,0) for the origininstance variable. The specified default must be a compile-time constant. This constructor supplies default values for all three instance variables.

this.origin = const Point(0, 0)と書くことで、originについてデフォルト値を設定することになります。設定されたデフォルト値はコンパイル時定数である必要があります。このコンストラクタは三つのインスタンス変数全てにデフォルト値を設定しています。


Improve the output

b2f84ff91b0e1396.png Add the following toString() function to the Rectangle class:

下記のtoString()メソッドをRectangleクラスに追加します。

@override
String toString() =>
      'Origin: (${origin.x}, ${origin.y}), width: $width, height: $height';

 


Use the constructor

b2f84ff91b0e1396.png Replace main() with the following code to verify that you can instantiate Rectangle using only the parameters you need:

main()関数内を下記のように修正して、必要な引数のみでのRectangelインスタンスの生成ができることを確認してみましょう。

main() {
  print(Rectangle(origin: const Point(10, 20), width: 100, height: 200));
  print(Rectangle(origin: const Point(10, 10)));
  print(Rectangle(width: 200));
  print(Rectangle());
}

cf1e10b838bf60ee.png Observation

  • The Dart constructor for Rectangle is one line of code, compared to 16 lines of code for equivalent constructors in the Java version.

DartのコードでのRectangelクラスのコンストラクタが1行であるのに対し、Javaバージョンで同等のコンストラクタの記述には16行が必要です。


Run the example

You should see the following output:

出力は下記のようになるはずです。

Origin: (10, 20), width: 100, height: 200
Origin: (10, 10), width: 0, height: 0
Origin: (0, 0), width: 200, height: 0
Origin: (0, 0), width: 0, height: 0

Problems?Check your code.


Factories, a commonly used design pattern in Java, have several advantages over direct object instantiation, such as hiding the details of instantiation, providing the ability to return a subtype of the factory’s return type, and optionally returning an existing object rather than a new object.

Javaでよく使われるデザインパターンであるファクトリーは、オブジェクトのインスタンス化の詳細を隠蔽し、ファクトリーの戻り値のサブタイプを返す機能を提供し、オプションで新しいオブジェクトではなく既存のオブジェクトを返すなど、(ノーマルなコンストラクタによる)直接的なオブジェクトのインスタンス化に比べていくつかの利点を持っています。

This step demonstrates two ways to implement a shape-creation factory:

このステップではshape-creation factoryの実装について二つの方法を示します。

  • Option 1: Create a top-level function.

Option1:トップレベル関数を定義する。

  • Option 2: Create a factory constructor.

Option 2:factoryコンストラクタを定義する。

For this exercise, you’ll use the Shapes example, which instantiates shapes and prints their computed area:

このエクササイズでは、Shapeクラスのサンプルを使います。Shapeクラスのインスタンスを生成して、面積を計算し、表示します。

import 'dart:math';

abstract class Shape {
  num get area;
}

class Circle implements Shape {
  final num radius;
  Circle(this.radius);
  num get area => pi * pow(radius, 2);
}

class Square implements Shape {
  final num side;
  Square(this.side);
  num get area => pow(side, 2);
}

main() {
  final circle = Circle(2);
  final square = Square(2);
  print(circle.area);
  print(square.area);
}

b2f84ff91b0e1396.png Open the Shapes example in DartPad.

In the console area, you should see the computed areas of a circle and a square:

コンソールに、円と正方形の面積が表示されていると思います。

12.566370614359172
4

cf1e10b838bf60ee.png Observations

  • Dart supports abstract classes.

Dartは抽象クラスをサポートしています。

  • You can define multiple classes in one file.

一つのファイルに複数のクラスを定義できます。

  • dart:math is one of Dart’s core libraries. Other core libraries include dart:core, dart:async, dart:convert, and dart:collection.

dart:mathはDartのコアライブラリの一つです。コアライブラリには他にdart:core, dart:async, dart:convert, and dart:collectionなどがあります。

慣例により、Dartのライブラリの定数はlowerCamelCase(例えば PI の代わりに pi )が使われます。詳しくはをPREFER using lowerCamelCase for constant names.ご覧ください。

  • The following code shows two getters that compute a value: num get area => pi * pow(radius, 2); // Circle num get area => pow(side, 2); // Square

下記のコードは円と正方形の面積(area)を計算するゲッターを示しています。


Option 1: Create a top-level function

b2f84ff91b0e1396.png Implement a factory as a top-level function by adding the following function at the highest level (outside of any class):

トップレベルの関数(全てのクラスの外側)として下記のようなファクトリを実装します。

Shape shapeFactory(String type) {
  if (type == 'circle') return Circle(2);
  if (type == 'square') return Square(2);
  throw 'Can\'t create $type.';
}

b2f84ff91b0e1396.png Invoke the factory function by replacing the first two lines in the main() method:

main()関数の最初の2行を下記のように(shapeFactory関数を使用したコードに)修正する。

  final circle = shapeFactory('circle');
  final square = shapeFactory('square');

Run the example

The output should look the same as before.

出力は一つ前と同じはずです。

cf1e10b838bf60ee.png Observations

  • If the function is called with any string other than 'circle' or 'square', it throws an exception.

関数(shapeFactory)に’circle’、’square’以外の文字列が渡された場合例外がスローされます。

  • The Dart SDK defines classes for many common exceptions, or you can implement the Exception class to create more specific exceptions or (as in this example) you can throw a string that describes the problem encountered.

Dart SDKでは色々な例外クラスを定義しています。あるいは自分でもっと具体的なExceptionクラスを実装することもできます。あるいはこのサンプルのように、問題の内容を示す文字列をスローすることも可能です。

  • When an exception is encountered, DartPad reports Uncaught. To see information that’s more helpful, wrap the code in a try-catch statement and print the exception. As an optional exercise, check out this DartPad example.

DartPadでは例外に出くわすとUncaughtとレポートされます。もっと有用な情報が必要ならコードをtry-catch文でラップして、例外をprint文などで出力しましょう。

DartPad exampleもご覧ください。

  • To use a single quote inside a string, either escape the embedded quote using slash ('Can\'t create $type.') or specify the string with double quotes ("Can't create $type.").

文字列リテラルの中でシングルクオーテーションを使用したい場合は、

「シングルクオーテーションをバックスラッシュでエスケープする」

「文字列リテラルをダブルクオーテーションを使って表現する」

のどちらかが必要です。

Problems?Check your code.


Option 2: Create a factory constructor

Use Dart’s factory keyword to create a factory constructor.

Dartのfactoryキーワードを使ってfactoryコンストラクタを定義しましょう。

b2f84ff91b0e1396.png Add a factory constructor to the abstract Shape class:

抽象クラスShapeにfactoryコンストラクタを追加しましょう。

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;
}

b2f84ff91b0e1396.png Replace the first two lines of main() with the following code for instantiating the shapes:

main()関数の最初の2行をShapeインスタンスをインスタンス化する下記のコードに修正します。

  final circle = Shape('circle');
  final square = Shape('square');

b2f84ff91b0e1396.png Delete the shapeFactory() function that you previously added.

shapeFactory()関数は不要になったので削除します。

cf1e10b838bf60ee.png Observation

  • The code in the factory constructor is identical to the code used in the shapeFactory() function.

factoryコンストラクタ内のコードはshapeFactory関数内のコードと同一です。

Problems?Check your code.


5. Implement an interface

The Dart language doesn’t include an interface keyword because every class defines an interface.

Dart言語にはinterfaceキーワードはありません。なぜなら全てのクラスは自動的にinterfaceとして宣言されるからです。

つまり普通にクラスとして定義すれば、そのクラスを抽象クラスとしても使える、ということ。

b2f84ff91b0e1396.png Open the Shapes example in DartPad (or continue using your copy).

このリンクを開いてください(あるいはここまでのコードを使い続けてください)

b2f84ff91b0e1396.png Add a CircleMock class that implements the Circle interface:

Circleクラスを実装(implement)したCircleMockクラスを追加します。

class CircleMock implements Circle {}

b2f84ff91b0e1396.png You should see a “Missing concrete implementations” error because CircleMock doesn’t inherit the implementationof Circle—it only uses its interface. Fix this error by defining the area and radius instance variables:

“Missing concrete implementations”が出てくると思います。なぜならCircleMockクラスはまだ、areaとradiusというメンバーを実装していないからです。

class CircleMock implements Circle {
  num area = 0;
  num radius = 0;
}

cf1e10b838bf60ee.png Observation

  • Even though the CircleMock class doesn’t define any behaviors, it’s valid Dart—the analyzer raises no errors.

CircleMockクラスが何もふるまい(メソッド)を定義しなくても、Dartとしては問題ありません。アナライザーはエラーを出しません。

  • The area instance variable of CircleMock implements the area getter of Circle.

CircleMockクラスのインスタンス変数areaは、Circleクラスのゲッターareaの実装です。

Problems?Check your code.


6. Use Dart for functional programming

In functional programming you can do things like the following:

関数的プログラミングでは下記のようなことができます。

  • Pass functions as arguments.

引数を関数に渡す。

  • Assign a function to a variable.

関数を変数に代入する。

  • Deconstruct a function that takes multiple arguments into a sequence of functions that each take a single argument (also called currying).

複数の引数を取る関数を、それぞれが単一の引数を取る一連の関数に分解する(currying とも呼ばれる)。

  • Create a nameless function that can be used as a constant value (also called a lambda expression; lambda expressions were added to Java in the JDK 8 release).

無名関数を定数値として使う(ラムダ式と呼ばれる、ラムダ式はJDK 8リリースで導入された)

Dart supports all those features. In Dart, even functions are objects and have a type, Function.

Dartはこれらの機能を全てサポートしています。Dartでは関数はFunction型(クラス)のオブジェクトです。

This means that functions can be assigned to variables or passed as arguments to other functions.

これは「関数を変数に代入することができる」また、「関数を別の関数に引数として渡すことができる」ということを意味します。

You can also call an instance of a Dart class as if it were a function, as in this example.

また、「Dartクラスのインスタンスを関数のように呼び出す」ということも可能です。このサンプルをご覧ください

The following example uses imperative (not functional-style) code:

下記のサンプルはインペラティブ(命令的)(functional-styleではない)コードです。

String scream(int length) => "A${'a' * length}h!";

main() {
  final values = [1, 2, 3, 5, 10, 50];
  for (var length in values) {
    print(scream(length));
  }
}

b2f84ff91b0e1396.png Open the Scream example in DartPad.

The output should look like the following:

出力は下記のようになるはずです。

Aah!
Aaah!
Aaaah!
Aaaaaah!
Aaaaaaaaaaah!
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah!

cf1e10b838bf60ee.png Observation

  • When using string interpolation, the string ${'a' * length} evaluates to “the character 'a' repeated lengthtimes.”

文字列補間を使用する場合、文字列 ${‘a’ * length} は “文字 ‘a’ を length 回繰り返したもの” と評価されます。


Convert imperative code to functional

b2f84ff91b0e1396.png Remove the imperative for() {...} loop in main() and replace it with a single line of code that uses method chaining:

main関数の中の、インペラティブ(命令的)なfor(){…}ループを削除して、代わりにメソッドチェーンを使用した一文を使います。

  values.map(scream).forEach(print);

Run the example

The functional approach prints the same six screams as the imperative example.

関数的アプローチにより命令的アプローチの場合と同じ結果がえ得られました。

Problems?Check your code.


Use more Iterable features

The core List and Iterable classes support fold(), where(), join(), skip(), and more. Dart also has built-in support for maps and sets.

コアのListクラスとIterableクラスはfold()、where()、join()、skip()などのメソッドをサポートしており、DartはMapやSetもサポートしています。

b2f84ff91b0e1396.png Replace the values.map() line in main() with the following:

main()関数のvalues.map()の箇所を下記のように修正します。

values.skip(1).take(3).map(scream).forEach(print);

Run the example

The output should look like the following:

結果は下記のようになります。

Aaah!
Aaaah!
Aaaaaah!

cf1e10b838bf60ee.png Observations

  • skip(1)skips the first value, 1, in the values list literal.

skip(1)は、リストリテラルvaluesの中の一番最初の1つの要素(値)、つまり1をスキップ(削除)します。

  • take(3)gets the next 3 values—2, 3, and 5—in the values list literal.

take(3)は、valuesの最初の三つの要素(値)、つまり2,3,5を取得します。

  • The remaining values are skipped.

残りの値はスキップされます。

Problems?Check your code.


7. Congratulations!

By completing this codelab, you gained knowledge of some differences between Java and Dart. Dart is easy to learn and, in addition, its core libraries and rich set of available packages increase your productivity. Dart scales well to large apps. Hundreds of Google engineers use Dart to write mission-critical apps that bring in much of Google’s revenue.

このコードラボでJavaとDartのいくつかの違いを確認できました。Dartは学習が容易で、なおかつDartkコアライブラリと利用可能なパッケージはあなたの生産性を向上させます。Dartは大規模なアプリになっても優れたスケーラビリティを発揮します。何百人ものGoogleのエンジニアが、Googleの収益の多くをもたらすミッションクリティカルなアプリケーションを書くためにDartを使用しています。


Next steps

A 20-minute codelab isn’t long enough to show you all of the differences between Java and Dart. For example, this codelab hasn’t covered:

20分のコードラボではJavaとDartの間の全ての違いを示すことのに十分ではありません。例えばこのコードラボでは下記のことはカバーしていません。

  • async/await, which allows you to write asynchronous code as if it were synchronous. Check out this DartPad example, which animates the calculation of the first five decimals of π.

async/await、これを使えば非同期的なコードを同期的なコードと同じように記述することができます。このDartPadサンプルをチェックしてください。

メソッドのカスケード記法。

Null aware演算子。

If you’d like to see Dart technologies in action, try the Flutter codelabs.

Dartの技術を実際に見てみたい方は、Flutter codelabsをお試しください。

Learn more

You can learn much more about Dart with the following articles, resources, and websites.

下記の記事、リソース、webサイトもご覧ください。

Articles

Resources

Websites

参考

https://developers.google.com/codelabs/from-java-to-dart?hl=en

カテゴリーDart

コメントを残す

メールアドレスが公開されることはありません。