[Kotlin] Scope Functions

neoneoneo·2024년 3월 11일
0

kotlin

목록 보기
31/49

Scope Functions란?

객체의 범위를 정의하여 코드 블록을 실행하는 다양한 함수들이 있다. 범위 Scope는 임시로, 코드를 편리하게 작성할 수 있도록 한다.

종류

let

var strNum = "10"
var result = strNum?.let {
    // 중괄호 안에서는 it으로 활용함
    Integer.parseInt(it)
}
println(result!!+1)

with

var alphabets = "abcd"
with(alphabets) {
//  var result = this.subSequence(0,2)
    var result = subSequence(0,2)
    println(result)
}

also

val result = "Hello, Kotlin".also {
    println(it) // 출력: Hello, Kotlin
}.length
println(result) // 출력: 12

apply

val result = StringBuilder().apply {
    append("Hello, ")
    append("Kotlin")
}.toString()
println(result) // 출력: Hello, Kotlin

run

		var totalPrice = run {
        var computer = 10000
        var mouse = 5000
        computer+mouse
    }
    println("총 가격은 ${totalPrice}입니다")
fun main() {
    var student = Student("참새", 10)
    student?.run {
        displayInfo()
    }
}
class Student(name: String, age: Int) {
    var name: String
    var age: Int    
    init {
        this.name = name
        this.age = age
    }    
    fun displayInfo() {
        println("이름은 ${name} 입니다")
        println("나이는 ${age} 입니다")
    }
}

반환 방법

  • 블록 수행 결과
    • run, with, let
  • 객체 자신
    • apply, also

it or this

  • it
    • let, also
  • this
    • run, with, apply

it은 다른 이름으로 변경 할 수도 있다.

// 잘못된 예시
Person().also {
	it.name = "한석봉"
	it.age = 40
  val child = Person().also {
	  it.name = "홍길동" // 누구의 it인지 모른다!
    it.age = 10 // 누구의 it인지 모른다!
  }
  it.child = child
}
// 수정한 예시
Person().also {
	it.name = "한석봉"
	it.age = 40
  val child = Person().also { c ->
	  c.name = "홍길동"
    c.age = 10
  }
  it.child = child

[TIL-240311]

profile
우당탕ㅌ앙개발기록

0개의 댓글