일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
- FastAPI
- BOF
- llm을 활용 단어장 앱 개발일지
- fastapi를 사용한 파이썬 웹 개발
- 백준
- 파이토치 트랜스포머를 활용한 자연어 처리와 컴퓨터비전 심층학습
- PCA
- Flutter
- ML
- BAEKJOON
- Widget
- BFS
- system hacking
- pytorch
- Stream
- Dreamhack
- MDP
- ARM
- Got
- MATLAB
- DART
- study book
- rao
- C++
- Computer Architecture
- Kaggle
- bloc
- Image Processing
- 영상처리
- Algorithm
- Today
- Total
Bull
[dart::method] Method Chaining 본문
dart: Method Chaining??
대문에 '?'가 붙은 이유는 dart에서 공식적으로 method chaining이란 개념을 명명하지 않았기 때문이다. method chaining은 동일한 객체를 참조해 사용하는데 연속해서 다른 메소드를 별도로 사용하는 방법을 말한다. 흔히 Java에서 사용하는 개념인데 dart에서도 list
, map
등 컬렉션의 메소드에서 혹은 then
과 같이 Future에서도 본 적이 있을 것이다. Java에서의 설명은 다음을 참고하면 된다.
https://www.geeksforgeeks.org/method-chaining-in-java-with-examples/
Method Chaining In Java with Examples - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
www.geeksforgeeks.org
어떻게 해석해야 하지?
이 개념은 흐름정도 알아놓는 게 좋다. 따라서 예제로 살펴보겠다.
void main() {
List<int> numbers = [1, 2, 3, 4, 5];
// List에서 체이닝 예시
var result = numbers
.map((number) => number * 2) // 모든 요소를 2배로
.where((number) => number > 5) // 5보다 큰 요소만 필터링
.toList(); // 결과를 List로 변환
print(result); // [6, 8, 10]
}
여기서 map
메소드와 Map 컬렉션과 헷갈릴만하다. 하지만 map
메소드는 mapping을 생각하면, map은 기존 컬렉션의 모든 요소에 특정 변환을 적용하고, 변환된 요소들로 구성된 새로운 컬렉션을 생성한다. 이 과정에서 원래 컬렉션은 변경되지 않고, 변환된 요소들이 담긴 새로운 Iterable이 반환된다.
where
을 통해 요소를 필터링 시키고 toList
를 통해 List로 반환시킨다.
then
.then()
은 비동기 작업의 결과를 처리할 때 사용되며, JavaScript의 Promise
에서 사용하는 .then()
과 유사한 방식으로 동작한다. Dart의 Future
클래스에서 제공되는 이 메소드를 통해 비동기 작업의 완료 후에 실행할 콜백 함수를 등록할 수 있다.
Future<int> fetchData() {
return Future.delayed(Duration(seconds: 2), () => 42);
}
void main() {
fetchData().then((value) {
print('The value is $value');
}).catchError((error) {
print('An error occurred: $error');
});
}
여기서 fetchData()
함수는 2초 후에 42
를 반환하는 Future
를 리턴하고, .then()
메소드는 이 Future
가 완료된 후에 실행될 콜백을 정의한다. 반환값을 그대로 콜백의 인자로 보내주겠다는 것이다.
이것을 좀만 더 변환해서 객체를 반환하고 콜백의 인자로 넣어주는 예시를 보겠다. 이것이 then 문법을 사용하는 게 편한 이유이다.
import 'dart:async';
class MyClass {
String data;
MyClass(this.data);
void printData() {
print('Data: $data');
}
}
Future<MyClass> getMyClassInstance() async {
return Future.delayed(Duration(seconds: 2), () {
return MyClass('Hello, World!');
});
}
void main() {
getMyClassInstance().then((instance) {
instance.printData();
});
}
getMyClassInstance
를 통해서 바로 인스턴스를 만들어준다. 그러면 그 만들어진 인스턴스를 then
의 콜백으로 전달하여 인라인으로 printData
를 호출할 수 있다.
'Computer Language > Dart' 카테고리의 다른 글
[Dart::Parallelism] 병렬 처리 사용 기본법 (Isolate) (0) | 2024.08.20 |
---|---|
[Dart::Stream] Stream을 비동기처리 한다는 게 무슨 뜻일까? with Bloc (0) | 2024.08.19 |
[Dart::Stream] broadcast method (0) | 2024.08.19 |
[Dart::Stream] listen method (0) | 2024.08.19 |
[Dart] Mixin은 언제 사용하나요? (1) | 2024.07.23 |