Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- producer
- cd
- JPA
- consumer
- Streams
- git
- ECS
- QueryDSL
- entity graph
- transactionaleventlistener
- PAGING
- offsetdatetime
- Kotlin
- kafka
- spring
- Entity
- mysql
- spring kafka
- K8s
- Spring Data JPA
- bean
- CodePipeline
- CI
- Kubernetes
- API
- mirror maker2
- Spring JPA
- topic생성
- AWS
- centos7
Archives
- Today
- Total
Yebali
Kotlin의 Static Method와 Function 본문
Static 이란?
Java에서 Static 키워드를 사용한다는 것은 메모리에 한번 할당되어 프로그램이 종료될 때 해제되는 것을 의미합니다.
Static 변수와 Static 메서드는 Static 메모리 영역에 존재하므로 객체가 생성되기 이전에 이미 할당이 되어 있습니다.
그렇기 때문에 객체의 생성 없이 바로 사용할 수 있습니다.
Kotlin에서는 static 키워드 대신 object와 companion object 키워드를 사용합니다.
Object
Object는 최초 사용시 자동으로 생성되고, 생성자도 필요하지 않다.
object Counter {
var count = 0
fun countUp() {
count++
}
fun clear() {
count = 0
}
}
fun main() {
println(Counter.count)
Counter.countUp()
Counter.countUp()
println(Counter.count)
Counter.clear()
println(Counter.count)
}
companion object
클래스 안에서 Object를 만들면 여러 개의 인스턴스들이 공통으로 사용하는 값이나 함수를 가질 수 있다.
class FoodPoll (val name: String) {
companion object {
var total = 0
}
var count = 0
fun vote() {
total++
count++
}
}
fun main() {
var a = FoodPoll("짜장")
var b = FoodPoll("짬뽕")
a.vote()
a.vote()
b.vote()
b.vote()
b.vote()
println("${a.name} : ${a.count}")
println("${b.name} : ${b.count}")
println("총계 : ${FoodPoll.total}")
}
'Kotlin' 카테고리의 다른 글
Kotlin의 nullable변수 처리 (0) | 2021.09.22 |
---|---|
Kotlin의 제너릭 (0) | 2021.09.22 |
Kotlin의 스코프 함수 (0) | 2021.09.22 |
Kotlin의 고차함수와 람다함수 (0) | 2021.09.22 |
Kotlin의 추상화와 인터페이스 (0) | 2021.09.22 |