11/1 금 - Dart문법 복습
기초문법
Dart는 객채지향언어 -> 모든 상수,변수 함수는 오브젝트로 다루어짐.
행의 끝은 세미콜론(;)이 필요 (swift나 코틀린이랑 다르다.) 함수는 중괄호{} 코멘트는 더블슬래쉬(//) , 그리고 로그출력을 위한 함수는 printf() 문자열은 싱글쿼테이션(')을 사용
변수종류
문자: String
숫자: number, int, double
불리언: boolean
열거형: List(Array), Set, Map
var키워드를 사용한 변수선언 - 타입추론
var name = '합천국밥';
var since = 1955;
var price = 1.2;
var menus = ['돼지국밥', '순대국밥', '순대모듬(특)', '수육'];
var image = {
'tags': ['돼지국밥'],
'url': '//path/to/kubab.jpg',
};
final, const 를 사용한 변수선언 - 불변하는 변수의 선언
final won = '원';
final String yen = '엔';
const price = 1000000;
const double convPrice = 0.812 * price;
컬렉션 타입
1. List - 인덱스로 특정원소에 접근 가능한 타입
List<Strng> menuList = ['돼지국밥', '순대국밥', '순대모듬(특)', '수육'];
// add: 아이템추가
menuList.add('술국');
// where: 필터링기능. 결과가 Iterable이 반환되므로 리스트로 변환해줌.
menuList.where((name) => name == '돼지국밥').toList();
// map: 각요소를 정의한 함수로 처리한 결과를 반환. 결과가 Iterable이 반환되므로 리스트로 변환해줌.
menuList.map((name) => '합천 $name').toList();
// reduce: 각요소를 정의한 함수로 처리하고 결과값을 다음 처리시 넘겨줌.
fianl allMenu = menuList.reduce((value, element) => $value + ',' $element);
// fold: reduce랑 같으나 반환형을 지정(변경)가능
fianl allMenuCont = menuList.fold<Int>(0, (value, element) => value + element.length);
2. Map - 키와 값으로 저장하는 사전형
var fruits = {
'apple': 'red',
'banana': 'yellow',
'grape': 'purple'
};
fruits['apple']); // 'red'
fruits['mango'] = 'orange';
3. Set - 중복을 허용하지 않고 순서보장이 안되는 리스트
var numbers = {1, 2, 3, 4, 4, 2};
numbers.add(5);
numbers.remove(3);
4. enum - 열거형, 일반적으로 switch랑 같이 사용
enum Season {
spring,
summer,
autumn,
winter,
}
var currentSeason = Season.summer;
switch (currentSeason) {
case Season.spring:
print('It\'s spring!');
break;
case Season.summer:
print('It\'s summer!');
break;
case Season.autumn:
print('It\'s autumn!');
break;
case Season.winter:
print('It\'s winter!');
break;
}
제어문
1. if
var number = 10;
if (number % 2 == 0) {
print('$number is even.');
} else {
print('$number is odd.');
}
2. for
for (var i = 0; i < 5; i++) {
print('Hello, Dart $i');
}
3. while
while (number > 0) {
print('Countdown: $number');
number--;
}
4. do-while
var number = 5;
do {
print('Countdown: $number');
number--;
} while (number > 0);
5. switch
var grade = 'A';
switch (grade) {
case 'A':
print('Excellent');
break;
case 'B':
print('Good');
break;
case 'C':
print('Average');
break;
case 'D':
print('Poor');
break;
default:
print('Invalid grade');
}
6. break, continue
for (var i = 0; i < 10; i++) {
if (i == 5) {
break; // Stops the loop
}
print('Number: $i');
}
for (var i = 0; i < 10; i++) {
if (i == 5) {
continue; // Skips the current iteration
}
print('Number: $i');
}
람다식 - 이름이 없는 익명함수?
(많은 언어에서 익명 함수와 람다 함수를 구분하지만 다트에서는 구분하지 않음)
함수 { } 에서 {} 대신 ⇒ 으로 기호를 변경하는것
객체지향프로그래밍
다트는 객체지향언어이므로 클래스, 인스턴스, 상속, 추상클래스, 인터페이스, 믹스인등을 지원
클래스, 인스턴스
class Person {
String name; // Field
// Constructor
Person(this.name);
// Method
void greet() {
print('Hello, I am $name');
}
}
void main() {
var john = Person('John'); // Instantiate the Person class
john.greet(); // Prints: Hello, I am John
}
상속
extends를 사용하여 상속받은 클래스를 정의할 수 있음
class Employee extends Person {
String department;
// Constructor
Employee(String name, this.department) : super(name);
// Overridden Method
@override
void greet() {
print('Hello, I am $name and I work in $department');
}
}
void main() {
var jane = Employee('Jane', 'HR'); // Instantiate the Employee class
jane.greet(); // Prints: Hello, I am Jane and I work in HR
}
추상클래스
여느언어와같이 추상메소드를 선언하여 상속으로 메소드정의를 강제할 수 있음
abstract class Shape {
double getArea(); // Abstract method
void printArea() {
print('The area is ${getArea()}');
}
}
class Circle extends Shape {
Circle(this.radius);
final double radius;
@override
double getArea() => 3.14 * radius * radius; // Concrete implementation of abstract method
}
void main() {
final circle = Circle(5);
circle.printArea(); // Prints: The area is 78.5
}
인터페이스
dart문법에서 다른점이 인터페이스도 class로 선언한다는 점
클래스랑 인터페이스랑 구분 - 인터페이스로 받을땐 implements 로 사용
class Printable {
void printValue() {}
}
class MyClass implements Printable {
final int value;
MyClass(this.value);
@override
void printValue() {
print('The value is $value');
}
}
void main() {
final myClass = MyClass(10);
myClass.printValue(); // Prints: The value is 10
}
믹스인
클래스를 재이용하기 위한 문법. 상속을 피하기 위해 필요
mixin Flyable {
void fly() {
print('I can fly!');
}
}
class Animal {
void eat() {
print('I can eat!');
}
}
class Bird extends Animal with Flyable {
void chirp() {
print('I can chirp!');
}
}
void main() {
Bird bird = Bird();
bird.eat(); // Prints: I can eat!
bird.fly(); // Prints: I can fly!
bird.chirp(); // Prints: I can chirp!
}
캡슐화
독특한 dart문법. 보통은 private라는 지시자를 사용하는데 dart에선 _를 prifix로
class BankAccount {
int _balance = 0; // private field
int get balance => _balance; // getter
void deposit(int amount) {
if (amount > 0) {
_balance += amount;
}
}
}
void main() {
var account = BankAccount();
account.deposit(100);
print(account.balance); // Prints: 100
}
다형성 - 객체지향의 핵심이라고 할수 있는 개념
abstract class Animal {
void makeNoise();
}
class Dog extends Animal {
@override
void makeNoise() {
print('Woof!');
}
}
class Cat extends Animal {
@override
void makeNoise() {
print('Meow!');
}
}
void main() {
List<Animal> animals = [Dog(), Cat()];
for (Animal animal in animals) {
animal.makeNoise();
}
}
예외처리 - 다른 언어와 차이점이 없음
void main() {
try {
int result = divideNumbers(10, 0);
print('The result is $result');
} catch (e) {
print('An error occurred: $e');
} finally {
print('End of try-catch');
}
}
int divideNumbers(int num1, int num2) {
if (num2 == 0) {
throw ArgumentError('You can\'t divide by zero!');
}
return num1 ~/ num2;
}
제네릭 - 제네릭을 이용하면 유연한 공통화작업이 가능. 무심결에 쓰던 List<String>, Map<int, String> 같은것들이 제네릭으로 만들어진 것
// Generic Class Example
class Box<T> {
T contents;
Box(this.contents);
}
// Generic Function Example
T first<T>(List<T> items) {
return items[0];
}
void main() {
var box1 = Box<int>(10);
print(box1.contents);
var box2 = Box<String>('Hello');
print(box2.contents);
var numbers = [1, 2, 3];
print(first(numbers));
var words = ['apple', 'banana', 'cherry'];
print(first(words));
}
'공부 일기 > TIL' 카테고리의 다른 글
Flutter 창업반 3주차 TIL2 - 라이브러리 이용, 동기/비동기 (3) | 2024.11.08 |
---|---|
Flutter 창업반 3주차 TIL1 - 예외처리, 오류 (0) | 2024.11.08 |
Flutter 창업반 2주차 TIL4 - 객체지향 프로그래밍 (0) | 2024.11.01 |
Flutter 창업반 2주차 TIL3 - 함수형 프로그래밍과 Dart (0) | 2024.11.01 |
Flutter 창업반 2주차 TIL2 - Dart 심화문법 (0) | 2024.11.01 |