Kotlin (코틀린)
Kotlin in A..Z (13) - 클래스
강태종
2020. 7. 15. 11:51
- 클래스 선언하기
코드
// 클래스 선언
class Something {
// 프로퍼티
val id:Long = 0
// 메서드
fun action() {
}
}
- 인스턴스 선언하기
생성자를 통해 인스턴스를 생성할 수 있다.
코드
val something = Something()
- 주 생성자
코드
// 주 생성자 정의
class Something constructor(_id:Long) {
val id: Long = _id
}
fun main() {
// 주 생성자로 인스턴스 생성
val something = Something(123L)
}
- constructor를 생략한 주 생성자
코드
// 주 생성자 정의
class Something(_id:Long) {
val id: Long = _id
}
fun main() {
// 주 생성자로 인스턴스 생성
val something = Something(123L)
}
- 프로퍼티를 포함한 주 생성자
코드
// 주 생성자 정의
class Something(val id:Long) {
}
fun main() {
// 주 생성자로 인스턴스 생성
val something = Something(123L)
}
- 주 생성자도 함수처럼 디폴트 값을 넣을 수 있다.
코드
// 디폴트값 정의
class Something(val id:Long = 0) {
}
fun main() {
val something0 = Something() // id = 0
val something1 = Something(123L) // id = 123
val something2 = Something(id = 12) // id = 12 를 명시
}
- init 블럭을 사용한 초기화
클래스가 생성될 때 초기화를 시킬 수 있는 블록
주 생성자는 블록을 가질 수 없기 때문에 init 블럭에서 초기화를 진행해야 한다.
코드
// 주 생성자 정의
class Something(val id:Long) {
init {
println("Something ID : $id")
}
}
fun main() {
val something = Something(123L)
}
결과
Something ID : 123
- 부 생성자 (constructor)
클래스는 부 생성자를 이용해 생성자를 여러개 정의할 수 있다.
주 생성자가 없는 부 생성자 정의
코드
class Something {
val id: Long
constructor(id: Long) {
this.id = id
}
constructor(id:String) {
this.id = id.toLong()
}
}
fun main() {
val something1 = Something(123)
val something2 = Something("123")
}
주 생성자가 있는 부 생성자 정의
코틀린에서 주 생성자가 있는 경우 부 생정자를 정의 할 때 꼭 주 생성자를 호출해야한다.
코드
class Something(var id: Long){
constructor() : this(0) {
}
constructor(id:String) : this(id.toLong()){
}
}
fun main() {
val something1 = Something(123)
val something2 = Something()
val something3 = Something("123")
}
- 메서드 오버로딩
같은 이름을 가진 함수가 여러개 있더라도 매개변수의 형태가 다르면 정의할 수 있다.
상황에 맞게 호출됨
코드
class Math {
fun add(x: Int, y:Int) = x + y
fun add(x: Int, y:Int, z:Int) = x + y + z
fun add(str1: String, str2:String) = str1.toInt() + str2.toInt()
}
fun main() {
val math = Math()
println(math.add(1, 2))
println(math.add(1, 2, 3))
println(math.add("12", "22"))
}
결과
3
6
34