728x90
[ 함수의 인자에 이름을 붙이자 ]
∘ 코틀린으로 작성한 함수를 호출할 때, 함수에 전달하는 인자 중 일부(또는 전부)의 이름을 명시할 수 있다.
fun main() {
// val area = getArea(3, 5)
val area = getArea(
width = 3,
height = 5
)
}
fun getArea(width: Int, height: Int): Int {
return width * height
}
[ default parameter ]
∘ 함수를 정의할때 인자에 default값을 지정할 수 있다.
∘ default값이 존재하는 인자는 호출할 때 제외 가능
fun main() {
getArea(width = 2, height = 4) // 2*4 = 8
getArea() // 3*5 = 15
getArea(4) // 4*5 = 20
getArea(height = 6) // 3*6 = 18
}
fun getArea(width: Int = 3, height: Int = 5): Int {
return width * height
}
[ 정적인 유틸리티 클래스 없애기: 최상위 함수와 파라미터 ]
∘ 클래스 내부에 포함시키기 어려운 코드가 많이 생긴다.
∘ 코틀린에서는 함수&프로퍼티를 파일의 최상위(클래스 밖)에 위치시킬 수 있다.
// Java
class Main {
public static void main(String[] args){
int price = Phone.price;
int doublePrice = Phone.getDoublePrice();
}
}
class Phone {
static int price = 3000;
static int getDoublePrice() {
return price * 2;
}
}
// kotlin
val price = 3000
fun getDoublePrice() = price * 2
class Main {
fun main() {
val price = price
val doublePrice = getDoublePrice()
}
}
728x90
'Kotlin > Kotlin In Action' 카테고리의 다른 글
[Kotlin] 3-2. 확장 함수 (extension function) (0) | 2022.06.03 |
---|---|
[Kotlin] 2-5. 코틀린의 예외 처리 (0) | 2022.05.15 |
[Kotlin] 2-4. 이터레이션: while & for (0) | 2022.05.15 |
[Kotlin] 2-3. 선택 표현과 처리 : enum과 when (0) | 2022.05.15 |
[Kotlin] 2-2. 클래스와 프로퍼티 (0) | 2022.04.03 |