Lesson2 : Functions

Yunny.Log ·2022년 9월 17일
0
post-thumbnail

statement (문) vs expression (식)

  • expression 은 "값(value)"을 만들어낸다.
  • 코틀린에서 if, when 등 루프를 제외한 대부분의 제어 구조 등은 자바와 달리 expression
val isUnit = println("This is an expression")
println(isUnit)
  • println 이라는 아이는 값이 아닌 행위인 아이지 , 이를 찍으면 kotlin.Unit이 나온다.

    Kotlin's Unit is equivalent to Java's void.

  • we'll write some code to assign a println() to a variable called isUnit, and then print it. Since println() does not return a value, it returns kotlin.Unit.!


  • Functions with block body must specify return types explicitly, unless intend to return Unit
    : 블럭이 있는 함수는 타입을 명시적으로 보여줘야 함
	fun printHello(name: String?): Unit {
    		println("Hi there!")
	}

Function arguments

Default parameters

  • Default values provide a fallback if no parameter value is passed.
    : 아무것도 안 넘어오면 보여줄 아이

fun drive(speed: String = "fast") {
   println("driving $speed")
}
    fun ggaeSongPyeon(args: String="깨송편") {
        print('\n'+args)
    }
    ggaeSongPyeon() # 아무것도 안 넣으면 기본 인자인 깨송편
    ggaeSongPyeon("콩송편")

  • 깨송편 먹구싶당

Required parameters

  • If no default is specified for a parameter, the corresponding argument is required.

Named arguments

fun reformat(str: String,
             divideByCamelHumps: Boolean,
             wordSeparator: Char,
             normalizeCase: Boolean = true)
reformat(str, divideByCamelHumps = false, wordSeparator = '_')

Compact functions

  • When a function returns a single expression, the curly braces can be omitted and the body is specified after a "=" symbol.
    : 단일문인 경우에, 한 줄에 쓸 수 있다

Lambdas and higher-order functions

Function types

  • function type 을 쓰는 syntax 는 “(Parameter types) -> Return type” 이다.

    waterFilter can be any function that takes an Int and returns an Int.

  • Fuction type with a receiver type : A.(B) -> C

Lambda expressions

  • Lambda expressions are function literals, which can be passed as an expression.
encodeMessage("acronym", { input -> input.toUpperCase() })

Function Reference

  • The :: operator lets Kotlin know that you are passing the function reference as an argument, and not trying to call the function.

:: operator

  • :: operator to pass a named function
  • it 는 고유어,

Higher-order functions

  • 하나 이상의 함수를 인자로 받기 & 함수를 결과로 반환
fun encodeMsg(msg: String, encode: (String) -> String): String {return encode(msg)
}

Scope Functions

  • Scope Functions 함수들을 람다식을 이용해서 호출하면 일시적인 Scope(범위)가 생김

  • 이 범위 안에서는 전달된 객체에 대해 "it" 또는 "this" 라는 Context Object를 통해서 접근

  • Scope Function에는 서로 다른 두 가지 주요 차이점

(1) Context Object를 참조하는 방법 (this, it)

  • Scope Function 람다식 내에서 Context Object는 실제 객체명 대신, "it" 또는 "this" 키워드로 접근
class Person (var name: String, var age: Int)

fun main() {
    val person = Person("홍길동", 30)
    
    //this로 참조
    person.run {
          println("이름 : ${name}") //this.name과 동일
    }
    
    //it로 참조
    person.let {
          println("이름 : ${it.name}")
    }
}
  • 유형 따라 다르다 (it 쓰는지, this 쓰는지)

this

   - run, with, apply 는 Context Object를 "this" 로 참조 
   - 따라서, 람다식 안에서는 일반 클래스 멤버처럼 사용할 수 있습니다.
  - this는 생략할 수 있지만, 만약 동일한 이름의 멤버가 있을 경우 구별할 수가 없기 때문에, 가급적이면 Context Object에 대해서는 this를 붙여서 사용
       class Person (var name: String, var age: Int)

fun main() {
    val person = Person("홍길동", 30)
    
    //this로 참조
    person.run {
          println("이름 : ${this.name}")
    }
}

it

  • let, also 는 Context Object를 "it" 로 참조
  • 따로 전달 인자명을 지정할 수도 있고, 지정하지 않으면 기본적으로는 "it" 로 접근
class Person (var name: String, var age: Int)

fun main() {
    val person = Person("홍길동", 30)
    
    //it로 참조
    person.let {
          println("이름 : ${it.name}")
    }
    
    //전달 인자명 지정해서 참조
    person.let { value ->
          println("이름 : ${value.name}")
    }
}

Return Value

  • apply, also는 Context Object 반환
  • let, run, with는 람다식 결과 반환

(2) Return value


느낀점

  • 희한한 포인트들이 많다, 근데 그 포인트들이 다 편리하다

reference

https://docs.google.com/presentation/u/0/
https://jjeda.tistory.com/21
https://aroundck.tistory.com/4869
https://0391kjy.tistory.com/25
https://medium.com/@la.place/higher-order-function-%EC%9D%B4%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80-1c61e0bea79

0개의 댓글

관련 채용 정보