Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 11 additions & 9 deletions docs/topics/fun-interfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ To declare a functional interface in Kotlin, use the `fun` modifier.

```kotlin
fun interface KRunnable {
fun invoke()
fun invoke()
}
```

Expand All @@ -25,7 +25,7 @@ For example, consider the following Kotlin functional interface:

```kotlin
fun interface IntPredicate {
fun accept(i: Int): Boolean
fun accept(i: Int): Boolean
}
```

Expand All @@ -34,9 +34,9 @@ If you don't use a SAM conversion, you will need to write code like this:
```kotlin
// Creating an instance of a class
val isEven = object : IntPredicate {
override fun accept(i: Int): Boolean {
return i % 2 == 0
}
override fun accept(i: Int): Boolean {
return i % 2 == 0
}
}
```

Expand All @@ -51,13 +51,13 @@ A short lambda expression replaces all the unnecessary code.

```kotlin
fun interface IntPredicate {
fun accept(i: Int): Boolean
fun accept(i: Int): Boolean
}

val isEven = IntPredicate { it % 2 == 0 }

fun main() {
println("Is 7 even? - ${isEven.accept(7)}")
println("Is 7 even? - ${isEven.accept(7)}")
}
```
{kotlin-runnable="true" kotlin-min-compiler-version="1.4"}
Expand All @@ -75,7 +75,9 @@ interface Printer {
fun print()
}

fun Printer(block: () -> Unit): Printer = object : Printer { override fun print() = block() }
fun Printer(block: () -> Unit): Printer = object : Printer {
override fun print() = block()
}
```

With callable references to functional interface constructors enabled, this code can be replaced with just a functional interface declaration:
Expand Down Expand Up @@ -110,7 +112,7 @@ typealias IntPredicate = (i: Int) -> Boolean
val isEven: IntPredicate = { it % 2 == 0 }

fun main() {
println("Is 7 even? - ${isEven(7)}")
println("Is 7 even? - ${isEven(7)}")
}
```

Expand Down