[Kotlin Bootcamp] 3: Functions ①

2020. 10. 7. 01:37개발공부/Kotlin

Kotlin Bootcamp : link

 

Kotlin Bootcamp for Programmers 3: Functions

There's a lot in this lesson, especially if you're new to lambdas. A later lesson revisits lambdas and higher-order functions. Note: You may have noticed that in Kotlin, as in some other languages, there is more than one correct way to do things. Making co

codelabs.developers.google.com

Java 메서드와 유사한 Kotlin의 Functions는 비교적 간결하며 편하다는 느낌을 받았습니다. 데이터 타입과 정해진 틀이 있는 Java보다 사용법이 훨씬 자유롭습니다. 

1) Functions 사용해 요일별 물고기 먹이 출력하기

import java.util.*

//fun을 써줘야 함. 콜론(:) 뒤엔 데이터 타입을 명시함
fun randomDay() : String {
    val week = arrayOf("Monday", "Tuesday", "Wednesday", "Thursday",
    "Friday", "Saturday", "Sunday")
    return week[Random().nextInt(week.size)]
}

fun fishFood (day : String) : String {
    return when (day) {
        "Monday" -> "flakes"
//        "Tuesday" -> food = "pellets"
        "Wednesday" -> "redworms"
        "Thursday" -> "granules"
        "Friday" -> "mosquitoes"
//        "Saturday" -> food = "lettuce"
        "Sunday" -> "plankton"
        else -> "nothing"
    }
}


fun feedTheFish() {
    val day = randomDay()
    val food = fishFood(day)
	//Java printf같은 기능을 $[변수명]이 해줌. String 안에서 가능하단 점이 Kotlin의 자유로운 면을 보여줌
	println("Today is $day and the fish eat $food")
    println("Change wather: ${shouldChangeWater(day)}")
}


2) Functions parameter(매개변수) default 설정 

parameter의 value를 정하지 않으면 자동 주입되는 default value를 설정할 수 있습니다. 오류를 줄여주는 기능 같은데 자칫하면 헷갈릴 수 있어 default value는 잘 명시해야할 것 같습니다.

//speed는 String타입의parameter, default value는 fast이다.
fun swim(speed: String = "fast") {
    println("swimming $speed")
}

3) Functions single-expression & when을 이용한 concise coding

Kotlin 코드의 특징은 간결하다 입니다. 축약된 코드를 보면 마음이 테트리스 끼워넣은 것처럼 편해집니다.

fun isTooHot(temperature: Int) = temperature > 30
//아래 function를 single-expression으로 나타낸 function 입니다.
/*-> fun isTooHot(temperature: Int) {
		return temperature > 30
	}*/
fun isDirty(dirty: Int) = dirty > 30
fun isSunday(day: String) = day == "Sunday"

fun shouldChangeWater (day: String, temperature: Int = 22, dirty: Int = 20) : Boolean {
    //when은 switch랑 비슷해서 when(day) 형태로 쓸 수도 있습니다.
    return when {
//        temperature > 30 -> true
//        dirty > 30 -> true
//        day == "Sunday" -> true
        isTooHot(temperature) -> true
        isDirty(dirty) -> true
        isSunday(day) -> true
        else -> false
    }
}

fun main(args: Array<String>) {
    feedTheFish()
    swim()
    swim("slow")
    swim(speed="turtle-like")
}

'개발공부 > Kotlin' 카테고리의 다른 글

[Kotlin Bootcamp] 3: Functions ② filters & lambdas  (0) 2020.10.17