Dartの変数型について

Flutterを使ったアプリ開発 プログラミング

型の推定

多くの場合、プログラムが走るときに変数の型が推測されます。つまり、変数は実行時にセットされた値に基づいて決められるのです。

この方法では、次のように、型が自動で決められます。(ex1.dart)

void main() {
  dynamic x = 1;
  if(x is int){
    print('integer');
  }
}
integer

しかし、途中で型の違う計算などをしようとすると、はじめに型が決まってしまっているため、エラーが出ます。

void main() {
  dynamic x = 'test';
  if(x is String){
    print('String');
  }
  x += 1;
}
String
Uncaught Error: TypeError: 1: type 'JSInt' is not a subtype of type 'String'

型のマッチング

型のマッチングを知るためには、「is」というキーワードを使います。

void main() {
  printType(23);
  printType('mark');
}

printType(dynamic d){
  if(d is int){
    print('Its an Integer');
  }
  if(d is String){
    print('Its a String');
  }
}
Its an Integer
Its a String

このように、型の一致を調べることができます。

型の情報

マッチングではなく、実行時の型を知る方法もあります。「runtimeType」オブジェクトを使うと、型を返してくれます。

void main() {
  var v1 = 10;
  print(v1.runtimeType);
  
  var v2 = 'hello';
  print(v2.runtimeType);
}
int
String

文字列(String)

文字列補間

Dartの最も便利な機能の1つが文字列補間です。文字列の中で${xxx}のように書くことで、変数を連結することができます。

class Person{
  String firstName;
  String lastName;
  int age;
  Person(this.firstName, this.lastName,this.age);
}

main(){
  Person p = new Person('mark','smith',22);
  print('The persons name is ${p.firstName} ${p.lastName} and he is ${p.age}');
}
The persons name is mark smith and he is 22

文字列リテラル

Dartでは、エスケープ文字を使うことができます。例えば「\n」は改行を意味します。これをただの文字列として認識させたいときは、文字列の前に「r」をつければよいのです。

main(){
  print('this\nstring\nhas\nescape\ncharacters');
  print('');
  print(r'this\nstring\nhas\nescape\ncharacters');
}
this
string
has
escape
characters

this\nstring\nhas\nescape\ncharacters
main(){
  double price = 100.75;
  print('Price is: \${price}');
}
Price is: $100.75

絵文字

絵文字も、文字列として使えます。次のサイトに、たくさんの絵文字とコードが乗っているので、参考にしてみてください。:https://www.compart.com/en/unicode/block/U+1F300

main(){
  var sunrise = '\u{1f305}';
  print(sunrise);
}
🌅
タイトルとURLをコピーしました