Skip to content

[Kotlin] 람다식으로 익명 클래스 만들기 #8

Description

@dkdud9261
interface A {
  fun a1()
  fun a2()
}

위와 같이 정의된 interface를 람다식으로 구현하기 위해서는 object 키워드를 사용할 수 있다.

val objectA = object : A {
  override fun a1() { println("a") }
  override fun a2() { println("a2") }
}

특별히 인터페이스에 메서드가 하나만 있는 경우 SAM(Single Abstract Method) 또는 Functional Interface 라고 부르며,
object 키워드를 생략하고 람다식으로 익명 클래스를 만들기 위해서는 fun interface 키워드로 인터페이스를 정의해야 한다.

fun interface B {
  fun b()
}

val objectB = B { println("b") }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions