Kotlin - this

이동수·2024년 9월 9일

Kotlin

목록 보기
16/33
post-thumbnail

this

생성자, 인스턴스 메소드 내에서만 사용가능

heap memory에 생성된 객체의 자기 참조 값을 가짐

용도

  • 은닉된 이름 사용
  • 자신의 참조 값을 전달
  • 자신의 참조 값은 리턴

class안에서 this를 쓰면 속성을 가르킨다??

fun main(){
    A(1)
}
class A(var a: Int){
    init {
        var a: Int =2
        println(this.a) //class 속성의 a = 1
        println(a) //init의 a = 2
    }
    fun print(){print(a)} //class 속성의 a = 1
    fun print2(){ 
        var a = 3
        println(this.a) //class 속성의 a = 1
        println(a) //print2()의 a = 3
    }
}

ex 1) 객체 2개 생성(circle1, circle2)

package kotlin_this
class Circle {
private var radius = 0.0
fun setRadius(radius: Double) {
this.radius = radius
}
fun displayArea() {
val result = String.format(
"원의 반지름 %.0f 의 넓이는 %.2f 입니다",
radius, (this.radius * this.radius) * Math.PI
)
println(result)
}
}
fun main() {
val circle1 = Circle()
circle1.setRadius(7.0)
circle1.displayArea()
val circle2 = Circle()
circle2.setRadius(9.0)
circle2.displayArea()
}

ex 2) 객체 1개 생성

package kotlin_this
class RCircle {
private var radius = 0.0
fun setRadius(radius: Double): RCircle {
this.radius = radius
return this
}
fun displayArea(): RCircle {
val result = String.format(
"원의 반지름 %.0f 의 넓이는 %.2f 입니다",
radius, (this.radius * this.radius) * Math.PI
)
println(result)
return this
}
}
fun main() { 
RCircle().setRadius(7.0).displayArea().setRadius(9.0).displayArea()
}

call back

객체와 객체끼리 쌍방향 통신을 함

class Order{
	private val productStatus = ProductStatus()
	fun takeOrder(goods: String){
		productStatus.checkProductStatus(this, goods)
	}
	fun checkProductsGoods(flag: Boolean){ //Back 되돌려줌 - callBack.checkProductsGoods(flag) 에서 
		if(flag){
			println("요청하신 상품을 주문했습니다")
		}else{
			println("죄송합니다. 현재 재고가 없네요")
		}
	}
}
class ProductStatus{
	private val products = HashMap<String, Int>()
	init {
		products["플레인요거트"] = 10
		products["그릭요거트"] =3
		products["블루베리요거트"] = 5
	}
	fun checkProductStatus(callBack : Order, goods: String) { // Call불러옴 - productStatus.checkProductStatus(this, goods) 에서
	var flag = false
	if(products.containsKey(goods) && products[goods]!! > 0) {
		if ((products[goods]!! - 1) < 1) {
			products[goods] = 10
		} else {
				products[goods] = products[goods]!! - 1
		}
		flag = true
	}
	callBack.checkProductsGoods(flag)
	}
}
fun main(){
	Order().takeOrder("그릭요거트")
}


객체 또는 람다 표현식의 현재 인스턴스를 참조하는데 사용

클래스 속성과 매개변수를 구별하거나 현재 인스턴스를 다른 메서드에 전달하는 데 자주 사용

0개의 댓글