Computer Language/Dart
[Dart] Extension Methods란?
Bull_
2024. 7. 15. 15:52
Extension Methods는 Dart 언어의 기능으로, 기존 클래스에 새로운 기능을 추가할 수 있는 방법입니다. 이 기능을 사용하면 기존 클래스를 수정하지 않고도 해당 클래스에 새로운 메서드를 추가할 수 있습니다.
// extension on String
// extension에 이름을 지정해주지 않아도 되지만 충돌방지와 명확한 구분을 위해 적용하는 게 좋습니다.
extension StringExtension on String {
String capitalize() {
if (this.isEmpty) {
return this;
}
return this[0].toUpperCase() + this.substring(1).toLowerCase();
}
}
void main() {
String text = "hello world";
print(text.capitalize()); // Hello world
}
capitalize는 "대문자로 쓰다"의 뜻으로 첫자를 Hello world로 출력합니다.
간단한 코드이므로 큰 설명은 하지 않겠습니다.