언어/Kotlin

Kotlin : 함수 선언과 호출

해리누나 2022. 6. 18. 06:03
728x90
반응형

1. Top Level 함수와 Member 함수

Top - Level - Function: '자유함수'라고도 불리는데 어디서든 자유롭게 호출이 가능하다.
 //  println() 이나 arrayOf() 함수
 
 // 예시
 println("오늘의 날씨는 37도입니다")
 
 val names = arrayOf("김하나","박둘","황셋")
Member - Function: '메서드'라고도 불리며 '.'을 통해 호출이 가능하다.
 (멤버 함수는 클래스, 오브젝트 또는 인터페이스 내부에 정의된다.)
//예시: sum 함수

    val numbers = arrayOf(1,2,3,4,5)
    val sum = numbers.sum()

    println(sum)

위에 예시들을 보면 알겠지만, 함수는 항상 어떠한 '값'을 반환하다. 함수 arrayOf()는 생성된 배열을 반환하고, sum은 계산된 합계(int형)을 반환하다. 구체적인 값을 반환할 수 없는 경우에는 unit을 반환하다. unit은 자바의 void처럼 생각하면 된다. (void와 같은 것이 아니다)

/*Function - Syntax*/

fun 함수이름 (매개변수1 : 자료형, 매개변수2 : 자료형) : 반환값자료형 {
  표현식
  return 반환값
}

//예시

fun sum(a: Int, b: Int): Int {
    return a + b
}


//원기둥의 넓이 구하기
fun totalSurfaceOfCylinder(radius : Double, height : Double) : Double{
     val areaOfCircle = PI * pow(radius,2.0)  //원의 넓이
     val sideAreaOfCylinder = 2 * PI * radius * height //원기둥의 옆넓이
        
     return 2 * areaOfCircle + sideAreaOfCylinder
}

 

 

2. 실습

https://bruders.tistory.com/16 에 썼던 실습문제를 다시 보자. 문제가 병에 있는 물로 잔을 가득 채운다면, 병에 남아있는 물은 얼마인가? 였는데 그 상태 그대로에서 잔이 하나 더 추가되었다고 가정해보자.

 

https://bruders.tistory.com/17 에 썼던 코드에 이어서 잔2에 대한 정보를 추가시켜보자.

fun main (args : Array <String>) {

    var currentBottleContent = 800
    
    var currentGlass1Content = 40
    val maxGlass1Content = 150
    
    var currentGlass2Content = 90
    val maxGlass2Content = 200
    

    val toBeFilled = maxGlass1Content - currentGlass1Content  //잔1에 채워져야 할 양

    if(currentBottleContent >= toBeFilled1){ //상황1. 병의 물이 잔을 가득 채울 만큼 충분
        currentGlass1Content += toBeFilled1
        currentBottleContent -= toBeFilled1
    }else{                                  //상황2. 충분하지 않음 
        currentGlass1Content += currentBottleContent
        currentBottleContent = 0
    }

	
    val toBeFilled2 = maxGlass2Content - currentGlass2Content  //잔2에 채워져야 할 양

    if(currentBottleContent >= toBeFilled2){ 
        currentGlass21Content += toBeFilled2
        currentBottleContent -= toBeFilled2
    }else{                                  
        currentGlass2Content += currentBottleContent
        currentBottleContent = 0
    }

}

이렇게 잔2에 대한 계산을 따로 쓴다면, 같은 코드를 계속 반복하고 있는 바보같은 짓을 하게 된다. 이를 해결하기 위해 함수를 이용하면 된다. 잔에 물을 부어주고, 그만큼 병에서 물을 빼주는 하나의 함수를 만들면, 어떤 잔이나 병이 추가되어도 이 함수만 호출하면 된다.

 

   //잔에 채워져야할 물의 양 구하기
   fun calculateAmount (maxGlassContent : Double, currentBottleContent : Double, currentGlassContent : Double ) : Double{

        var amount = maxGlassContent - currentGlassContent

        if(currentBottleContent < amount){
            amount = currentBottleContent
        }

        return amount
    }


    fun pourWater (maxGlassContent : Double, currentBottleContent : Double, currentGlassContent : Double) : Unit{

        val toBeFilled = calculateAmount(maxGlassContent, currentBottleContent, currentGlassContent)

        currentBottleContent -= toBeFilled
        currentGlassContent += toBeFilled

    }

함수를 만든다면 이와 비슷할 것이다. 그런데 오류가 하나 있다. 함수가 받는 매개변수는 value값으로 변하지 않는 변수이기 때문에 pourWater 함수 내 currentBottleContent와 currentGlassContent의 값은 변할수 없는 값이기에 오류가 뜬다.

 

오류

    fun pourWater (maxGlassContent : Double, currentBottleContent : Double, currentGlassContent : Double) : Unit {

        val toBeFilled = calculateAmount(maxGlassContent, currentBottleContent, currentGlassContent)
        
        val newBottleContent = currentBottleContent - toBeFilled
        val newGlassContent =  currentGlassContent + toBeFilled

        println("현재 잔의 물의 양은 $newGlassContent ml입니다." )
        println("현재 병의 남은 물의 양은 $newBottleContent ml입니다." )

    }

그 값에 새로운 변수(newBottleContent, newGlassContent) 를 할당해주면 된다.

 

결과

 

 

 

출처:

내용: 학교 교수님 (Christian Kohls) 강의

728x90
반응형

'언어 > Kotlin' 카테고리의 다른 글

Kotlin : 클래스 (Class)  (0) 2022.09.02
Kotlin : 객체 (Object)  (0) 2022.06.24
Kotlin : 제어문 if 와 when  (0) 2022.06.17
Kotlin : 변수 var 과 val  (0) 2022.06.16
Kotlin 기초 : 자료형 (Data type)  (0) 2022.06.15