중괄호 블록안에 it으로 자신의 객체를 전달하고 수행된 결과를 반환
새로운 객체 = 객체.let{
외부메소드(it)
it.메소드()
it.프로퍼티
}
var strNum = "10"
// result에는 Int형 정수 10이 들어감
var result = strNum?.let {
// 중괄호 안에서는 it으로 활용함
//it = strNum을 가리킴
Integer.parseInt(it)
}
println(result!!+1)
fun main() {
var str = "abdc" //문자열
var temp = str.let{ //중괄호 안의 내용을 temp라는 변수에 저장함
it.length //str.length
}
println(temp) //str.length 출력
}
중괄호 블록안에 this로 자신의 객체를 전달하고 코드를 수행
this는 생략가능하며, 반드시 null이 아닐 때만 사용
with(객체){
this.메소드() // 객체의 메소드()
메소드() // 객체의 메소드(), 위랑 동일
this.프로퍼티 // 객체의 프로퍼티
프로퍼티 // 객체의 프로퍼티, 위랑 동일
외부메소드(객체의메소드)
외부메소드(객체의프로퍼티)
}
fun main() {
var alphabets = "abcd"
with(alphabets) { //abcd 문자열에서
// var result = this.subSequence(0,2)
var result = subSequence(0,2) //abc를 잘라내 새로운 문자열 객체를 만든다.
println(result) //"abc" 문자열 객체
}
}
fun main() {
var idx = 100
with(idx){
var strIdx = toString() //idx.toString을 strIdx에 저장
println(strIdx is String)
}
}
fun main() {
var str = "asfsadc"
with(str){
println(length) //str.length 출력
}
}
apply와 함께 자주 사용
중괄호 블록안에 it으로 자신의 객체를 전달하고 객체를 반환
새로운 객체 = 객체.also{
it.메소드()
it.프로퍼티
외부메소드(it)
}
fun main() {
var student = Student("참새", 10) //Student 클래스 객체 생성
var result = student?.also { //student가 null인지 확인하고, null이 아닐 때만 alse 내용 참조
it.age = 50 //Student.age = 50으로 초기화
}
result?.displayInfo() //null이 아닐 때만 displayInfo() 메소드 실행
student.displayInfo() //student의 displayInfo() 메소드 실행
}
class Student(name: String, age: Int) { //name과 age를 파라미터로 받는 Student 클래스
var name: String
var age: Int
//명시적으로 주생성자를 작성해 초기화를 진행
init {
this.name = name //name 프로퍼티 초기화
this.age = age //age 프로퍼티 초기화
}
fun displayInfo() { //이름과 나이를 출력하는 메소드
println("이름은 ${name} 입니다")
println("나이는 ${age} 입니다")
}
}
중괄호 블록안에 this로 자신의 객체를 전달하고 객체를 반환
주로 객체의 상태를 변화시키고 바로 저장하고 싶을때 사용
새로운 객체 = 객체.apply{
객체.프로퍼티 = 변화시킬 값
}
fun main() {
var student = Student("참새", 10)
var result = student?.apply {
student.age = 50
}
result?.displayInfo()
student.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{
메소드() // 객체의 메소드()
프로퍼티 // 객체의 프로퍼티
외부메소드(객체의메소드)
외부메소드(객체의프로퍼티)
}
새로운 객체 = run{
연산할 내용
외부 메소드()
외부 프로퍼티
}
with와 달리 null체크 수행 가능
fun main() {
var student = Student("참새", 10)
student?.run { //student 객체가 null이 아닐 때 중괄호 안의 내용 실행
displayInfo() //student.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} 입니다")
}
}
fun main() {
var totalPrice = run {
var computer = 10000
var mouse = 5000
computer+mouse
}
println("총 가격은 ${totalPrice}입니다")
}
https://kotlinlang.org/docs/scope-functions.html
https://kotlinworld.com/255