목록Dev/Kotlin (11)
Learn & Record
지연 초기화코틀린은 지연 초기화를 사용하는데 이는 클래스의 코드에 Nullable 처리가 남용되는 것을 방지해 줌.1. lateinit개발을 하다 보면 클래스 안에서 변수(프로퍼티)만 Nullable로 미리 선언하고 초기화(생성자 호출)를 나중에 해야 할 경우가 있는데,이럴 경우 lateinit 키워드를 사용할 수 있음.1) Nullable로 선언하는 일반적인 방법일바적인 선언 방식으로 처음에 null 값을 입력해두고, 클래스의 다른 메서드 영역에서 값을 입력함. class Person { var name: String? = null init { name = "Jane" } fun process() { name?.plus(..
7. 제네릭 제네릭 Generics은 입력되는 값의 타입을 자유롭게 사용하기 위한 도구, 다음은 실제 MutableList의 선언부. public interface MutableList : List, MutableCollection 클래스명 옆에부분에 String 같은 특정 타입이 지정되면 클래스 내부에 선언된 모든 E에 String 타입으로 지정. 결과적으로 var list: Array가 var list: Array으로 변경이 되는 것. 이렇게 설계된 클래스는 주로 구현하는 용도로 사용하며 컬렉션이나 배열에서 입력되는 값의 타입을 특정하기 위해 다음과 같이 사용. var list: MutableList = mutableListOf("abc", "def", "ghi") fun testGenerics() ..
1. 패키지 패키지는 클래스와 소스 파일을 관리하기 위한 디렉토리 구조의 저장 공간. 현재 클래스가 어떤 패키지(디렉토리)에 있는지 표시. 디렉토리가 계층 구조로 만들어져 있으면 점(.)으로 구분해서 각 디렉토리를 모두 나열해줌 package 메인 디렉토리. 서브 디렉토리 class 클래스 { } 이 디렉토리 구조라면 윈도우의 파일 탐색기에서 보면 메인 디렉토리 아래에 서브 디렉토리가 있고, 서브 디렉토리 안에 실제 코드가 있음 클래스.kt 파일이 있음 하나의 패키지에 여러 개의 파일을 생성할 수 있기 때문에 '서로 관계가 있는 파일을 동일한 패키지로' 만들어두면 관리가 용이. 2. 추상화 프로그래밍을 하기 전 개념 설계를 하는 단계에서는 클래스의 이름과 클래스 안에 있음 직한 기능을 유추해서 메서드 이..
1. 상속과 확장 클래스의 상속과 확장 코틀린은 클래스의 재사용을 위해 상속을 지원, 상속을 개념적으로 접근하면 상당히 어렵지만, 사용 측면에서 바라보면 이해가 쉬움 상속을 사용하는 예를 들면 안드로이드는 Activity라는 클래스가 미리 만들어져 있고, 이 Activity 클래스 내부에는 글자를 쓰는 기능, 그림을 그리는 기능, 화면에 새로운 창을 보여주는 기능이 미리 정의되어 있음 상속이 있기에 이런 기능을 직접 구현하지 않고 Activity 클래스를 상속받아 약간의 코드만 추가하면 앱에 필요한 기능을 추가할 수 있음 상속은 코드를 재활용하는 측면도 있지만, 코드를 체계적으로 관리할 수 있기 때문에 규모가 큰 프로젝트로 효과적으로 설계할 수 있음 1. 클래스의 상속 상속 대상이 되는 부모 클래스는 o..
1. Compaion object class Dog { companion object { var name: String = "None" fun printName() { println("Dog 이름은 ${name}입니다.") } } fun walk() { println("Dog가 뛰어갑니다.") } } fun main() { Cat.name = "mikey" Cat.printName() // Cat의 이름은 mikey입니다. // companion object 안의 코드 사용하기 Dog.name = "Linda" Dog.printName() // Dog 이름은 Linda입니다. // Dog.walk() // companion object 밖에 선언된 메서드는 사용하지 못함 // companion objec..
1. Class 1. 코틀린에서 사용되는 클래스의 기본 구조 class 클래스이름 { var 변수 fun 함수() { 코드 } } 2. 클래스 코드 작성하기 클래스를 만들기 위해서는 먼저 클래스의 이름을 정하고, 이름 앞에 class 키워드를 붙여서 만들 수 있음 클래스 이름 다음에는 클래스의 범위를 지정하는 중괄호({})가 있어야 함 이 중괄호를 스코프 scope라고 하는데, 클래스에서 사용했기 때문에 클래스 스코프라고 함 class 클래스이름 { // 클래스 스코프 class scope } '몇몇 예외'는 있지만 대부분의 코드는 클래스 스코프 안에 작성 작성된 클래스를 사용하기 위해서는 생성자라고 불리는 함수가 호출되어야 하는데, 코틀린은 프라이머리 primary와 세컨더리 Secondary 2개의 ..