Kotlin 기초 #5 Scope함수

0

야! 너두 코틀린

목록 보기
5/13

🚓 1. run

Run 스코프 함수는 Alias를 쓸수없다.
Result값을 반환했을때, 12가 나온다

    val resultRun =    seoulPeople.persons.run {
            add(Study09.Person("scott", "01012345678", "123"))
            add(Study09.Person("sw", "01012345678", "123"))
            add(Study09.Person("swe", "01012345678", "123"))
           12  
    }

🐱‍👤 2. let

run으로 하면 너무축약될때 let을 이용해 지칭을 해준다.
it을 Alias 할수있다.

val resultLet =  seoulPeople.persons.let { person -> //run과 let의 차이점
person.add(Study09.Person("scott", "01012345678", "123"))
person.add(Study09.Person("ws", "01012345678", "123"))
person.add(Study09.Person("swe", "01012345678", "123"))
12
}

🎉 3. apply

apply는 한가지 빼고 같다. 바로 결과값이 함수로 나오는것

        val resultApply =   seoulPeople.persons.apply{
            add(Study09.Person("scott", "01012345678", "123"))
            add(Study09.Person("sw", "01012345678", "123"))
            add(Study09.Person("swe", "01012345678", "123"))
            11
        }
 //결과값은 Person 객체이다.

🛹 4. also

also 또한 apply의 let버전이다.


val resultLet =  seoulPeople.persons.also { person -> 
 person.add(Study09.Person("scott", "01012345678", "123"))
person.add(Study09.Person("ws", "01012345678", "123"))
person.add(Study09.Person("swe", "01012345678", "123"))
12
 }


 //결과값은 Person 객체이다.

🚖 5. with

with는 블럭의 return 값이 필요하지 않을 때 사용한다.
그래서 주로 객체의 함수를 여러 개 호출할 때 그룹화하는 용도로 활용된다.

        with(binding){
           button.setOnClickListner{}   //binding.button.setOnClickListner{}이다.
           imageView.setImageLevel(50)
           textView.text = "반가워워"
      }
profile
쉽게 가르칠수 있도록 노력하자

0개의 댓글