0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Dart ファイル内に「_」プライベートなんて無い話

0
Last updated at Posted at 2021-09-16

スコープはとても大事なわけです。

Dartは通常、変数の前に「_」(アンダーバー)を入れると、ローカル変数とみなされると言われています。私もそれを信じて、今まで生きてきました。関数も同様です。具体的には、

{
  int _iyann= 0 ;
}

は、カッコ外から参照できないと思っていたんですね。ところが、事実は違います。

Dartのプライベート事情

次のコードを走らせます。

class Human {
  int _sumikko = 1;
  int oppiroge = 2;
}

main() {
  Human taro = Human();
  print(taro.oppiroge); //2がプリントされる
  print(taro._sumikko); //1がプリントされる
}

お分かりいただけたでしょうか?このように、Dartにおけるプライベートなんてあったもんじゃありません。

以下の質問でも書かれています。

引用

Every Dart app is a library, even if it doesn’t use a library directive. The >import and library directives can help you create a modular and shareable code >base.

ライブラリとしてなら、プライベートとして機能すると言うことですね。つまり先程のコードを分割して、

human.dart
class Human {
  int _sumikko = 1;
  int oppiroge = 2;
}
main.dart
import "human.dart";
main() {
  Human taro = Human();
  print(taro.oppiroge); //2がプリントされる
  print(taro._sumikko); //Error
}

となるわけです。ファイルスコープのみというわけでしょうか。

以上です。

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?