혼자 있고 싶네요. 모두 나가주세요.
[Kotlin]003. Destructuring declarations와 Data classes 본문
[Kotlin]003. Destructuring declarations와 Data classes
아무것도몰라양 2017. 9. 26. 20:01Destructuring declarations (비구조화 선언)
처음에는 잘 이해가 되지 않았다. 예제의 요지는 내부 변수에 간단하게 접근하여 선언할 수 있다는 것이다. 이를 destructing declarations이라고 하는 것 같다.
Pair Class는 내부적으로 operator를 overloading 하고 있다. 따라서 사용자가 기존에 있던 operator를 재정의 할 수 있다. 예제에서 component1()
과 component2()
는 예약어이다. 뭔지 한참 들여다봤네... 각각의 변수를 순서대로 의미하는 예약어가 되겠다. 그렇게 component1()
과 component2()
는 순서대로 내부 변수를 return하게 된다. 예제에서 val (num,name)
으로 간단하게 destructing 후 선언하는 것을 확인 할 수 있다.
Data Classes
어떤 클래스의 내부 변수에 자유롭게 접근하는 모습이다. 엄청 유연하다.
Map
앞서 배운 클래스를 가지고 노는 법을 응용해 보았다. model을 생성하고, 해시맵 인스턴스를 만든 뒤 for에서 멋지게 뽑아내었다. 위 코드의 결과는 다음과 같다.
key = one, name = 철수, index = 1
key = two, name = 영희, index = 2
Data Classes - auto generated funtions
Data Classes는 다양한 자동 생성 함수들을 가지고 있다고 한다. component functions, toString(), equals(), hashCode() 그리고 copy()가 그것이다.
위의 결과는 다음과 같다.
User(name=Alex, id=1)
user == secondUser: true
user == thirdUser: false
User(name=Alex, id=1)
User(name=Max, id=1)
User(name=Alex, id=2)
User(name=Max, id=2)
'타닥타닥 > Kotlin Extention' 카테고리의 다른 글
[Kotlin]002. 기본 문법 후려치기 - 2 (0) | 2017.09.19 |
---|---|
[Kotlin]001. 기본 문법 후려치기 - 1 (0) | 2017.09.19 |