2020/8/27 Dart : tour>>classes>>Methods〜の訳

Contents

Classes

 

Using class members

 

Using constructors

 

Getting an object’s type

 

Instance variables

 

Constructors

 


Methods

Methods are functions that provide behavior for an object.

メソッドはオブジェクトの振る舞いを提供する関数です。

Instance methods

Instance methods on objects can access instance variables and this. The distanceTo() method in the following sample is an example of an instance method:

オブジェクトのインスタンスメソッドはインスタンス変数とthisにアクセスできます。下記のサンプルのdistanceTo()メソッドはインスタンスメソッドの具体例です。

import 'dart:math';

class Point {
  double x, y;

  Point(this.x, this.y);

  double distanceTo(Point other) {
    var dx = x - other.x;
    var dy = y - other.y;
    return sqrt(dx * dx + dy * dy);
  }
}

Operators

Operators are instance methods with special names. Dart allows you to define operators with the following names:

演算子は特別な名前のインスタンスメソッドです。Dartでは下記の名前の演算子を定義することができます。

< + | >>>
> / ^ []
<= ~/ & []=
>= * << ~
- % >> ==

Note: You may have noticed that some operators, like !=, aren’t in the list of names. That’s because they’re just syntactic sugar. For example, the expression e1 != e2 is syntactic sugar for !(e1 == e2).

注意 : != などのいくつかの演算子が上記の表に記載されていません。なぜならそれらの表現は糖衣構文だからです。例えば、e1 != e2という表現は、!(e1 == e2)の糖衣構文です。

 

An operator declaration is identified using the built-in identifier operator. The following example defines vector addition (+) and subtraction (-):

演算子の宣言はビルトインのoperator識別子により認識されます。下記のサンプルはVectorクラスのインスタンスに対する加算演算子と減算演算子です。

class Vector {
  final int x, y;

  Vector(this.x, this.y);

  Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
  Vector operator -(Vector v) => Vector(x - v.x, y - v.y);

  // Operator == and hashCode not shown.
  // ···
}

void main() {
  final v = Vector(2, 3);
  final w = Vector(2, 2);

  assert(v + w == Vector(4, 5));
  assert(v - w == Vector(0, 1));
}

 


Getters and setters

Getters and setters are special methods that provide read and write access to an object’s properties.

ゲッターとセッターは、オブジェクトのプロパティへの読み取りと書き込み機能を提供する特別なメソッドです。

 

Recall that each instance variable has an implicit getter, plus a setter if appropriate.

各インスタンス変数には、暗黙のゲッターと、必要に応じてセッターがあることを覚えておいてください。

 

You can create additional properties by implementing getters and setters, using the get and set keywords:

さらにgetとsetキーワードを使って追加的にプロパティを実装することができます。

class Rectangle {
  double left, top, width, height;

  Rectangle(this.left, this.top, this.width, this.height);

  // Define two calculated properties: right and bottom.
  // rightとbottom : 二つのcalculated propertiesを定義する。
  double get right => left + width;
  set right(double value) => left = value - width;
  double get bottom => top + height;
  set bottom(double value) => top = value - height;
}

void main() {
  var rect = Rectangle(3, 4, 20, 15);
  assert(rect.left == 3);
  rect.right = 12;
  assert(rect.left == -8);
}

With getters and setters, you can start with instance variables, later wrapping them with methods, all without changing client code.

ゲッターとセッターを使えば、インスタンス変数から始めて、後でメソッドでラップすることができ、すべてクライアントコードを変更することなく行えます。

 

Note: Operators such as increment (++) work in the expected way, whether or not a getter is explicitly defined. To avoid any unexpected side effects, the operator calls the getter exactly once, saving its value in a temporary variable.

注意:increment (++)のような演算子は、ゲッターが明示的に定義されているかどうかに関わらず、期待される方法で動作します。予期せぬ副作用を避けるために、演算子はゲッターを一度だけ呼び、その値を一時変数に保存します。

 


Abstract methods

Instance, getter, and setter methods can be abstract, defining an interface but leaving its implementation up to other classes. Abstract methods can only exist in abstract classes.

インターフェイスの定義だけはするがその実装は別のクラスでしたい場合、インスタンス、ゲッターメソッド、セッターメソッドは抽象化することができます。抽象メソッドは抽象クラス内にのみ存在します。

 

To make a method abstract, use a semicolon (;) instead of a method body:

メソッドを抽象メソッドにするには、メソッドボディの代わりにセミコロンのみを付けます。

abstract class Doer {
  // Define instance variables and methods...
  // インスタンスフィールドとメソッドの定義...

  void doSomething(); // Define an abstract method.
  //抽象メソッドの定義。
}

class EffectiveDoer extends Doer {
  void doSomething() {
    // Provide an implementation, so the method is not abstract here...
    // 継承先で抽象メソッドの実装を記述する。
  }
}

 


Abstract classes

Use the abstract modifier to define an abstract class

抽象クラスを定義する時にabstract修飾子を使います。

 

a class that can’t be instantiated.

抽象クラスを用いてインスタンスを生成することはできません。

 

Abstract classes are useful for defining interfaces, often with some implementation.

抽象クラスはインターフェイスを定義するのに便利です。通常は抽象クラスを実装した具体的なクラス(インスタンス化できるクラス)をいくつか定義します。

 

If you want your abstract class to appear to be instantiable, define a factory constructor.

抽象クラスをインスタンス化可能に見せたい場合は、ファクトリコンストラクタを定義します。

 

Abstract classes often have abstract methods. Here’s an example of declaring an abstract class that has an abstract method:

抽象クラスは抽象メソッドを持つことが多いです。以下のサンプルで抽象メソッドを持つ抽象クラスの例を示します。

abstract class AbstractContainer {
  // Define constructors, fields, methods...

  void updateChildren(); // ←抽象メソッド
}
//↑のクラスは抽象クラスなのでAbstractContainerのインスタンスは作れない。

 


Implicit interfaces

Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements.

すべてのクラスは、そのクラスとそのクラスが実装するインターフェースのすべてのインスタンスメンバを含むインターフェースを暗黙のうちに定義しています。

 

If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.

Bの実装を継承せずにBのAPIをサポートするクラスAを作りたい場合、クラスAはBのインターフェイスを実装する必要があります。

 

A class implements one or more interfaces by declaring them in an implements clause and then providing the APIs required by the interfaces. For example:

クラスは、1つまたは複数のインターフェースをimplementsキーワードで宣言し、 インターフェースが必要とするAPIを提供(実装)することによって、インターフェースを実装します。例えば

// A person. The implicit interface contains greet().
class Person {
  // In the interface, but visible only in this library.
  final String _name;

  // Not in the interface, since this is a constructor.
  Person(this._name);

  // In the interface.
  String greet(String who) => 'Hello, $who. I am $_name.';
}

// An implementation of the Person interface.
class Impostor implements Person {
  String get _name => '';

  String greet(String who) => 'Hi $who. Do you know who I am?';
}

String greetBob(Person person) => person.greet('Bob');

void main() {
  print(greetBob(Person('Kathy')));
  print(greetBob(Impostor()));
}

 

Here’s an example of specifying that a class implements multiple interfaces:

下記は複数のインターフェイスを実装するクラス(Point)の例です。

class Point implements Comparable, Location {...}

 


Extending a class

Use extends to create a subclass, and super to refer to the superclass:

extendsキーワードを使ってサブクラスを定義します。superキーワードを使ってスーパークラスを参照します。

class Television {
  void turnOn() {
    _illuminateDisplay();
    _activateIrSensor();
  }
  // ···
}

class SmartTelevision extends Television {
  void turnOn() {
    super.turnOn();
    _bootNetworkInterface();
    _initializeMemory();
    _upgradeApps();
  }
  // ···
}

For another usage of extends, see the discussion of parameterized types in generics.

extendsの他の使い方については、genericsのparameterized typesをご覧ください。


Overriding members

Subclasses can override instance methods (including operators), getters, and setters.

サブクラスはインスタンスメソッド(演算子も含む)・ゲッター・セッターをオーバーライドできます。

 

You can use the @overrideannotation to indicate that you are intentionally overriding a member:

意図的にメンバーをオーバーライドしていることを明示的に示すために@overrideアノテーションを使うことができます。

class Television {
  // ···
  set contrast(int value) {...}
}

class SmartTelevision extends Television {
  @override
  set contrast(num value) {...}
  // ···
}

An overriding method declaration must match the method (or methods) that it overrides in several ways:

オーバーライド先のメソッドの宣言はオーバーライド元のメソッドといくつかの方法で適合する必要がある。(オーバーライドのルールがあるのでそれに従う必要がある。それが下記)

 

  • The return type must be the same type as (or a subtype of) the overridden method’s return type.

「返り値の型」は「オーバーライド元のメソッドの返り値の型」と同じか、あるいはサブタイプでなければならない。

 

  • Argument types must be the same type as (or a supertype of) the overridden method’s argument types. In the preceding example, the contrast setter of SmartTelevision changes the argument type from int to a supertype, num.

「オーバーライド先の引数の型」は「オーバーライド元の引数の型」と同じか、あるいはスーパータイプである必要がある。一つ前のサンプルで例えると、SmartTelevisionクラスのcontrastセッターは、(スーパータイプのcontrastの型である)int型から、num型に変更している。

(intクラスはnumクラスのサブクラス。)

 

  • If the overridden method accepts n positional parameters, then the overriding method must also accept n positional parameters.

オーバーライド元のメソッドがn個のポジショナルパラメーターを持つ場合、オーバーライド先のメソッドもn個のポジショナルパラメーターが必要。

 

  • A generic method can’t override a non-generic one, and a non-generic method can’t override a generic one.

ジェネリックメソッドは非ジェネリックメソッドをオーバーライドできません。非ジェネリックメソッドはジェネリックメソッドをオーバーライドできません。

 

Sometimes you might want to narrow the type of a method parameter or an instance variable.

メソッドの引数、あるいはインスタンス変数の型を狭めたい場合があるかもしれません。

 

This violates the normal rules, and it’s similar to a downcast in that it can cause a type error at runtime.

これは通常のルールに違反しており、ダウンキャストのようなことなので、キャストに失敗した場合は実行時エラーが発生します。

 

Still, narrowing the type is possible if the code can guarantee that a type error won’t occur.

それでもキャスト失敗が起こらないことが保証できるケースでは型を狭めることも可能です。

 

In this case, you can use the covariant keyword in a parameter declaration. For details, see the Dart language specification.

この場合は、引数の宣言にcovariantキーワードを使います。詳しくはDart language specificationをご覧ください。

 

Warning: If you override ==, you should also override Object’s hashCode getter. For an example of overriding ==and hashCode, see Implementing map keys.

==演算子をオーバーライドする場合、オブジェクトのhashCodeゲッターも一緒にオーバーライドすべきです。==とhashCodeのオーバーライドの具体例は、Implementing map keysをご覧ください。


noSuchMethod()

工事中🏗

 


Extension methods

Extension methods are a way to add functionality to existing libraries.

Extension methodsは既存のライブラリに機能を追加する方法です。

 

You might use extension methods without even knowing it.

あなたは気づかずにextension methodを使っている可能性があります。

 

For example, when you use code completion in an IDE, it suggests extension methods alongside regular methods.

例えば、IDEでコード補完を使うと、通常のメソッドと一緒にextension methodも提案されます。

 

Here’s an example of using an extension method on String named parseInt() that’s defined in string_apis.dart:

下記の例は、Stringクラスのextension methodであるparseInt()です。(string_apis.dart)

import 'string_apis.dart';
...
print('42'.padLeft(5)); // Use a String method.
print('42'.parseInt()); // Use an extension method.

For details of using and implementing extension methods, see the extension methods page.

さらに詳しい情報は、extension methods pageをご覧ください。


Enumerated types

Enumerated types, often called enumerations or enums, are a special kind of class used to represent a fixed number of constant values.

列挙型は、よくenumerationsあるいはenumsと呼ばれます。特別な種類のクラスで、定まった数の固定値(constant)を表すのに使われます。

 

Note: All enums automatically extend the Enum class. They are also sealed, meaning they cannot be subclassed, implemented, mixed in, or otherwise explicitly instantiated.

注意 : 全てのenumは自動的にEnumクラスのサブクラスとなります。これらのenumはsealedなものとなります。つまり、enumをサブクラス化・実装・ミックスインすることはできません。また、enumをインスタンス化することもできません。

 

Abstract classes and mixins can explicitly implement or extend Enum, but unless they are then implemented by or mixed into an enum declaration, no objects can actually implement the type of that class or mixin.

抽象クラスとmixinはEnumを明示的に実装または継承することができますが、その後enum宣言によって実装またはミックスされない限り、どのオブジェクトもそのクラスまたはmixinの型を実際に実装することができません。


Declaring simple enums

To declare a simple enumerated type, use the enum keyword and list the values you want to be enumerated:

シンプルな列挙型を宣言するには、enumキーワードを使い、含めたい値をリストします。

enum Color { red, green, blue }

 

Tip: You can also use trailing commas when declaring an enumerated type to help prevent copy-paste errors.

ヒント:列挙型を宣言する際に、末尾にカンマをつけると、コピーペーストのエラーを防ぐことができます。

 


Declaring enhanced enums

Dart also allows enum declarations to declare classes with fields, methods, and const constructors which are limited to a fixed number of known constant instances.

Dartでは、列挙型宣言で、フィールド、メソッド、およびconstコンストラクターを使用してクラスを宣言することもできます。コンストラクターは、既知の定数インスタンスの固定数に制限されています。

 

To declare an enhanced enum, follow a syntax similar to normal classes, but with a few extra requirements:

enhanced enumを宣言するには、基本的に通常のクラスの宣言方法に従いますが、いくつかの追加の要件を守る必要があります。

 

  • Instance variables must be final, including those added by mixins.

インスタンス変数は、mixinによって追加されたものも含め、finalでなければなりません。

 

生成的コンストラクタはconstコンストラクタでなければなりません。

 

ファクトリーのコンストラクタは、固定された既知の列挙型のインスタンスのうちの1つだけを返すことができます。

 

  • No other class can be extended as Enum is automatically extended.

自動的にEnumクラスのサブクラスとなるので、他のクラスを継承することはできません。

 

  • There cannot be overrides for index, hashCode, the equality operator ==.

index , hashCode , ==演算子をオーバーライドすることはできません。

 

  • A member named values cannot be declared in an enum, as it would conflict with the automatically generated static values getter.

enumの中にvaluesという名前のメンバーを宣言することはできません。自動的に生成されるゲッターvaluesと競合(名前が被る)してしまうからです。

 

  • All instances of the enum must be declared in the beginning of the declaration, and there must be at least one instance declared.

列挙型のすべてのインスタンスは、宣言の最初に宣言する必要があり、少なくとも1つのインスタンスが宣言されている必要があります。

 

Here is an example that declares an enhanced enum with multiple instances, instance variables, a getter, and an implemented interface:

以下は、複数のインスタンス、インスタンス変数、ゲッター、および実装されたインタフェースを持つenhanced enumを宣言する例です。

enum Vehicle implements Comparable<Vehicle> {
  //↓全てのインスタンスをenum定義の最初に宣言する。
  car(tires: 4, passengers: 5, carbonPerKilometer: 400),//80
  bus(tires: 6, passengers: 50, carbonPerKilometer: 800),//16
  bicycle(tires: 2, passengers: 1, carbonPerKilometer: 0);//0

  //↓コンストラクタはconstコンストラクタにする。
  const Vehicle({
    required this.tires,
    required this.passengers,
    required this.carbonPerKilometer,
  });

  //↓インスタンス変数(フィールド)は全てfinalにする。
  final int tires;
  final int passengers;
  final int carbonPerKilometer;

  int get carbonFootprint => (carbonPerKilometer / passengers).round();

  @override
  int compareTo(Vehicle other) => carbonFootprint - other.carbonFootprint;
}

 

Version note: Enhanced enums require a language version of at least 2.17.

Enhanced enumの使うにはDartバージョン2.17以降が必要です。


Using enums

Access the enumerated values like any other static variable:

(クラスの)staticフィールドにアクセスするように、列挙型の値にアクセスできます。

final favoriteColor = Color.blue;
if (favoriteColor == Color.blue) {
  print('Your favorite color is blue!');
}

 

Each value in an enum has an index getter, which returns the zero-based position of the value in the enum declaration. For example, the first value has index 0, and the second value has index 1.

列挙型のそれぞれの値がindexゲッターを持っています。indexゲッターは、enumの宣言の中での宣言の順番通り0から順にポジションとして割り振られます。例えば一番最初の値がindex 0、二番目の値がindex 1です。

assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);

 

To get a list of all the enumerated values, use the enum’s values constant.

enumの全ての値を要素として持つリストを取得するために、values定数を使います。

List<Color> colors = Color.values;
assert(colors[2] == Color.blue);

 

You can use enums in switch statements, and you’ll get a warning if you don’t handle all of the enum’s values:

switch文の中でenumを使うことができます。それにより、全てのenumの要素を使用していない時に警告で知らせてもらえます。

var aColor 
= Color.blue;

switch (aColor) {
  case Color.red:
    print('Red as roses!');
    break;
  case Color.green:
    print('Green as grass!');
    break;
//default節が無いと警告が発生する。
  default: // Without this, you see a WARNING.
    print(aColor); // 'Color.blue'
}

 

If you need to access the name of an enumerated value, such as 'blue' from Color.blue, use the .nameproperty:

列挙型のそれぞれの値の名前にアクセスする必要がある場合、例えばColor.blueの’blue’にアクセスしたい場合、.nameプロパティを使います。

print(Color.blue.name); // 'blue'

 


Adding features to a class: mixins

工事中🏗

 


Class variables and methods

工事中🏗

 

 

参考

language-tour

コメントを残す

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