2020/11/11 Type test operators、Assignment operatorsの訳

 

Type test operators

as 演算子

is 演算子

is! 演算子

上記の演算子は実行時の型を調べるために使えます。

Operator Meaning
as Typecast (also used to specify library prefixes)
is True if the object has the specified type

objectがその型である場合にtrueを返す。

is! False if the object has the specified type

objectがその型である場合にfalseを返す。

objがT型のインターフェースを実装している時、

obj is T

はtrueとなります。例えば、

obj is Object

は常にtrueです。

abstract class AbsCls{}

class ACls implements AbsCls{}

class SubACls extends ACls{}

void main(){
  ACls var1=ACls();
  SubACls var2=SubACls();
  
  print(var1 is ACls); //true
  print(var1 is AbsCls); //true
  print(var2 is SubACls); //true
  print(var2 is ACls); //true
  print(var2 is AbsCls); //true
}

オブジェクトの型がその型であることが確実な場合に限り、as演算子を使用してオブジェクトを特定のタイプにキャストします。例:

(emp as Person).firstName = 'Bob';

オブジェクトがT型であるかどうかわからない場合は、オブジェクトを使用する前に、is演算子を使用してタイプを確認してください。

if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}

 

 注: コードは同等ではありません。empがnullの場合、またはPerson型でない場合、最初の例(asでキャスト)は例外をスローします。2番目(isで型チェック)は何もしません。

参考

https://dart.dev/guides/language/language-tour#type-test-operators



Assignment operators

As you’ve already seen, you can assign values using the = operator. To assign only if the assigned-to variable is null, use the ??= operator.

すでに見てきたように、=演算子を使用して値を割り当てることができます。 割り当て先変数がnullの場合にのみ割り当てるには、??= 演算子を使用します。

下記のサンプルでいうと変数a,bが代入先、割り当て先。

//null-safety無し

void main(){
  int a=5;
  //aの値は5。aの値はnullではない。なので10は代入されない。
  a ??=10;

  print(a); //5
  
  int b=null;
  //bの値はnull。なので10が代入される。
  b ??=10;

  print(b); //10
}

//↓repeatという名のメソッドの定義。(animation_controller.dart)

TickerFuture repeat({ double? min, double? max, bool reverse = false, Duration? period }) {
  //引数minが渡されていない(省略された)、あるいはnullが渡された場合、minにlowerBoundが代入される。
  //引数minにnullでない値が渡された場合lowerBoundは代入されない。
  min ??= lowerBound;
  max ??= upperBound;
  period ??= duration;
  
  //...
  //...

  return _startSimulation(_RepeatingSimulation(_value, min, max, reverse, period!, _directionSetter));
  //ということで、↑のminには、repeatメソッドの引数minにnullでない値が渡された場合はそれが使われる。
  //引数省略、あるいはnullが渡された場合はlowerBoundが使われる、ということになる。
}

Compound assignment operators such as += combine an operation with an assignment.

+ =などの複合代入演算子は、演算と代入を組み合わせます。

= –= /= %= >>= ^=
+= *= ~/= <<= &= |=

 

参考

https://dart.dev/guides/language/language-tour#assignment-operators

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です