250x250
반응형
05-11 14:06
Today
Total
«   2024/05   »
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
Notice
Recent Posts
Recent Comments
Link
Archives
관리 메뉴

Bill Kim's Life...

[Dart] Variables(변수) 본문

CS(컴퓨터 과학)/Dart

[Dart] Variables(변수)

billnjoyce 2020. 8. 19. 14:24
728x90
반응형
Dart 언어에서의 Variables(변수)에 대하여 살펴봅니다.

 

 

#. 구독 대상

  • Dart 언어를 처음 접하시면서 공부해보고 싶으신 분
  • 플러터(Flutter) 개발에 관심이 있어나 해보고 싶으신 분
  • 멀티 플랫폼 모바일 앱 개발을 시작하고 싶으신 분
  • 기타 소프트웨어 개발과 지식에 관심이 있으신 모든 분들

 

 


 

Variables

 

기본 변수에 대한 선언은 크게 아래와 같습니다.

var name = 'Bob';

dynamic name = 'Bob';

String name = 'Bob';


var a = 1; // int
var b = 2.2; // double
var c = 'String'; // String
var d = "String2": // String
var e = false; // bool 

var v_a = 3;
v_a = 'ccc' // 타입 변경 불가, 에러

dynamic d_a = "bbb";
d_a = 1; // String에서 int 타입 변환


 

var : 변수값 지정 시 자동으로 타입 지정(타입 추론), 한번 지정 후 다른 타입과의 변수값 복사 및 호환 불가(한번 지정 후 타입 변경 불가)

dynamic : 변수값 지정 시 자동으로 타입 지정(타입 추론), 한번 지정 후 다른 타입의 변수값 설정 시 타입 변경 가능

String : 명시적으로 문자형으로 변수 타입 지정

 

 

 

 

Final vs Const

 

Dart에서도 final과 const라는 키워드를 통하여 변수가 아닌 상수를 선언할 수 있습니다.

기본적인 final과 const의 정의를 살펴보면 아래와 같습니다.

 

  • final : 변하지 않는 값(immutable + 런타임 선언 가능)
  • const : 변하지 않는 값(imutable + 컴파일 타임 선언)
final double pi = 3.141592;
const double e = 2.71828;

final DateTime now_final = DateTime.now(); // 문제 없음
const DateTime now_const = DateTime.now(); // 컴파일 에러, DateTime의 생성자가 const로 선언되어 있지 않기 때문에 인스턴스화시에 const 키워드 사용 불가

const List<String> companies = [];
final List<String> languages = [];

companies.add('Google'); // 컴파일 에러

languages.add('dart'); // 문제 없음
languages = ['Java']; // 컴파일 에러

 

기본적으로 final과 const는 상수 선언을 위하여 사용되는 키워드로서 한번 값이 지정되면 수정할 수 없는 것이 특징입니다.

하지만 두 키워드에서는 약간의 차이점이 있습니다. 차이점을 한번 살펴보면 아래와 같습니다.

 

  • const는 컴파일 시에 final 은 런타임 시에 상수 값을 설정할 수 있다.
  • 런타임 시에 상수 값이 정해지는 특징에 따라서 final은 위에 코드 예시에서(DateTime.now()) 에러가 발생하지 않는다.
  • List 타입의 경우에도 final로 선언된 상수는 객체 추가 시에는 문제가 없으나 변경 시에는 컴파일 에러가 발생한다.
  • List 타입의 경우에 const는 객체 변경 및 추가가 모두 불가하다.
  • 인스턴스 변수(instance variable)는 final이 될 수 있지만 const는 사용할 수 없습니다

 

 


 

 

 

변수 타입(Built-in types)

 

그렇다면 Dart 언어에서 제공되는 기본 내장 타입에 대하여 살펴보겠습니다.

 

Numbers

 

Dart에서는 아래와 같이 두가지 형태의 숫자형 타입을 제공합니다.

 

int

Integer values no larger than 64 bits, depending on the platform. On the Dart VM, values can be from -263 to 263 - 1. Dart that’s compiled to JavaScript uses JavaScript numbers, allowing values from -253 to 253 - 1.

=> 최대 64비트 형태의 정수형 숫자 타입, 구동되는 플랫폼에 따라서 크기는 유동적

 

double

64-bit (double-precision) floating-point numbers, as specified by the IEEE 754 standard.

=> 64비트 실수형 숫자 타입

 

var x = 1;
var hex = 0xDEADBEEF;

var y = 1.1;
var exponents = 1.42e5;

double z = 1; // Equivalent to double z = 1.0.

// 명시적 타입 캐스팅
int a1 = 1;
double b1 = a1 as double;

// String -> int
var one = int.parse('1');
assert(one == 1);

// String -> double
var onePointOne = double.parse('1.1');
assert(onePointOne == 1.1);

// int -> String
String oneAsString = 1.toString();
assert(oneAsString == '1');

// double -> String
String piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == '3.14');

assert((3 << 1) == 6); // 0011 << 1 == 0110
assert((3 >> 1) == 1); // 0011 >> 1 == 0001
assert((3 | 4) == 7); // 0011 | 0100 == 0111

const msPerSecond = 1000;
const secondsUntilRetry = 5;
const msUntilRetry = secondsUntilRetry * msPerSecond;

 

String

 

Dart에서 제공하는 기본 문자형 타입은 String으로서 UTF-16 코드 문자를 지원합니다.

기본적으로 single qoute, double qoute를 구분하지 않습니다.

final str1 = 'hello';    // single qoute
final str2 = "hello2";   // double qoute

var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'Itescaped_code#39;s easy to escape the string delimiter.';
var s4 = "It's even easier to use the other delimiter.";

var s = 'string interpolation';

assert('Dart has $s, which is very handy.' ==
    'Dart has string interpolation, ' +
        'which is very handy.');
assert('That deserves all caps. ' +
        '${s.toUpperCase()} is very handy!' ==
    'That deserves all caps. ' +
        'STRING INTERPOLATION is very handy!');

 

 

Booleans

 

true 및 false 값을 저장하기 위한 타입으로 bool 타입이 있습니다

 

bool test; 
test = 12 > 5; 
print(test);  // true

var str = 'abc'; 
if(str) { 
   print('String is not empty'); 
} else { 
   print('Empty String'); 
} 

 

 


 

 

 

오늘은 Dart 언어에서의 변수에 대해서 종류와 타입에 대하여 살펴보았습니다.

 

감사합니다.

 

 

 

 

 

 

 

 

 


[참고 자료(References)]

 

[1] A tour of the Dart language : dart.dev/guides/language/language-tour

[2] Dart: final 과 const :medium.com/dartlang-korea/dart-final-과-const-bc8c6c024ef4

[3] [Dart] 다트 기본 문법 정리 1편 (자료형, 연산자, 주석) : blockdmask.tistory.com/393

[4] Dart — 기본 문법 : medium.com/hongbeomi-dev/dart-기본-문법-1b54cdb83b09

[5] Dart Programming Tutorial : www.tutorialspoint.com/dart_programming/index.htm

728x90
반응형

'CS(컴퓨터 과학) > Dart' 카테고리의 다른 글

[Dart] Control flow statements(제어문)  (0) 2020.08.20
[Dart] Operators(연산자)  (0) 2020.08.19
[Dart] Collection : List & Set & Map  (0) 2020.08.19
[Dart] 기초 문법  (0) 2020.08.19
[Dart] 개요 및 컨셉  (0) 2020.08.19
Comments