Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

dart - What are the semantics of _internal?

I keep seeing references to _internal in examples like the following:

class Symbol {
    final String name;
    static Map<String, Symbol> _cache;

    factory Symbol(String name) {
        if (_cache == null) {
        _cache = {};
     }

     if (_cache.containsKey(name)) {
        return _cache[name];
     } else {
        final symbol = new Symbol._internal(name);
        _cache[name] = symbol;
        return symbol;
      }
    }

  Symbol._internal(this.name);
}

I've gathered from the code that it's a privately accessible constructor. The last line Symbol._internal(this.name); seems a bit confusing because it appears to be a statement within the class body and not within a method body, leading me to believe it's actually the internal constructor definition without a method body.

Are my assumptions correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The _internal construction is just a name often given to constructors that are private to the class (the name is not required to be ._internal you can create a private constructor using any Class._someName construction).

For example the following code only allows you to create new persons from outside the class using a caching constructor:

class Person {

    final String name;
    static Map<String,Person> _cache;

    factory Person(String name) {
        if(_cache === null) {
            _cache = new Map<String,Person>();
         }
         if(_cache[name] === null]) {
            _cache[name] = new Person._internal(name); 
         }
         return _cache[name];
    }
   
    Person._internal(this.name);
}

In general Dart treats any _construction as private to either the class or the library that contains it. For example you can define as a global function like this:

_globalToThisLibaryOnly() {
    print("can only be called globally within this #library");
}

which can be called from any file that is sourced within the library that defines it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...