아래의 글은 드미트리 제메로프, 스베트라나 이사코바 저/오현석역,『Kotlin in Action』,에이콘출판사(2017)의 내용을 기반으로 작성하였습니다.

 

람다 : 다른 함수에 넘길 수 있는 작은 코드 조각

A lambda expression is a short block of code which takes in parameters and returns a value

Lambdas are code blocks enclosed in curly braces

람다 식은 주로 컬렉션을 다룸

코틀린에는 함수 호출시 맨뒤에 있는 인자가 람다 식이라면 그 람다를 괄호 밖으로 빼낼수 있음

람다 파라미터 이름을 디폴트 이름 it

 


val sum = { x: Int, y: Int -> x + y }

println(sum(1, 2))

{ println(42) }()

run { println(42) }

val peopleList = listOf(Person("Alice", 29), Person("Bob", 31))

peopleList.maxBy(it.age)

peopleList.maxBy(Person::age)

peopleList.maxBy({p: Person -> p.age})

peopleList.maxBy() {p: Person -> p.age}

peopleList.maxBy {p: Person -> p.age}

peopleList.maxBy { p -> p.age }

val nameList = peopleList.joinToString( seperator = " ", 
	transform = { p: Person -> p.name})

peopleList.joinToString(" ") { p.Person -> p.name }


val sum = { x: Int, y: Int -> 
	println("computing sum")
    x + y
    }
    
fun printWith(messageC: Collection<String>, prefix: String) {
	messageC.forEach {
    	println(" $prefix $it ")
    }
}

fun printCount(responses: Collection<String>) {
	var clientErrors = 0
    var serverErrors = 0
    responses.forEach {
    	if (it.startWith("4")) {
        	clientErrors++
        } else if (it.startWith("5")) {
        	serverErrors++
        }
    }
    
    println("$clientErrors $serverErrors")
}

// 변경 가능한 복사
class Ref<T>(var value: T)

// val 변경 불가능
val counter = Ref(0)



// 변경 불가능한 변수지만 내부 필드 값은 변경 가능
// list 의 내부 값 변경과 동일
val inc = { counter.value++}

// var 변경 가능 
var counter = 0

var inc = { counter++ }

// var 변경 가능 함수
var counter = Ref(0) 클래스 인스턴스에 넣음.


 

멤버 참조 :  member reference

자바의 method reference

최상위 함수 참조

확장 함수 참조

생성자 참조 : constructor reference


peopleList.maxBy(Person::age)

// memer reference

fun salute() = println("salute")

run(::salute)

// constructor reference

data class Person(val name: String, val age: Int)

val createPerson = ::Person

val p = createPerson("Alice", 26)

// 확장 함수 reference

fun Person.isAdult() = age > 21

val predicate = Person::isAdult

// bound memer reference

val p = Person("Colin", 34)

val personAgeFunction = Person::age

println(personAgeFunction(p))

val personAgeFunction= p::age

println(personAgeFunction())

 

코틀린이 보통 람다를 무명 클래스로 컴파일 하지만 그렇다고 람다 식을 사용할 때 마다 새로운 클래스가 만들어지지 않는다

람다가 변수를 포획하면 생성되는 시점마다 새로운 무명 클래스가 생긴다

즉 실행 시점에 무명 클래스 생성에 따른 부가 비용이 소요

람다를 사용하는 구현은 똑같은 작업을 수행하는 일반 함수를 사용한 구현보다 덜 효율적

 

java lambda

colinkang.tistory.com/61?category=951152

 

CH03 Lambda expression, CH04 Stream

아래의 글은 라울-게이브리얼 우르마, 마리오 푸스코, 앨런 마이크로프트 저/우정은 역, 『모던 자바 인 액션』,한빛미디어(2019), CH01의 내용을 기반으로 작성하였습니다. 람다 •표현식 •(파라

colinkang.tistory.com

 

 

www.w3schools.com/java/java_lambda.asp

 

Java Lambda Expressions

Java Lambda Expressions Java Lambda Expressions Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and

www.w3schools.com

kotlinlang.org/docs/reference/lambdas.html

 

Higher-Order Functions and Lambdas - Kotlin Programming Language

 

kotlinlang.org

 

+ Recent posts