Skip to content

Commit

Permalink
better SAM explanation
Browse files Browse the repository at this point in the history
  • Loading branch information
stephenbmfj committed Mar 7, 2019
1 parent fff6d21 commit b63a154
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions intro/src/main/java/io/mfj/kotlinnight/intro/SAM.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,35 @@ package io.mfj.kotlinnight.intro
import java.io.File
import kotlin.concurrent.thread

// Java SAM (Single Abstract Method) interfaces can be called with a lambda.
object SAM {

@JvmStatic
fun main( args:Array<String> ) {

// Thread's constructor takes a Runnable, which has a single abstract method, "run"

// Here is how we would do that with an anonymous object:
Thread(
object:Runnable {
override fun run() {
println( "Hello world [${Thread.currentThread().name}]" )
}
}
).start()

// It is much nicer if we just pass a lambda:
Thread {
println( "Hello world [${Thread.currentThread().name}]" )
}.start()

thread {
println( "Hello World [${Thread.currentThread().name}]" )
}

// Tangent: this is so common, that Kotlin has an extension function
// to create threads with lambda, and gives other useful arguments:
thread(start = true, name = "hello-thread",isDaemon = false) {
println( "Hello World ${Thread.currentThread().name}]" )
}

// File.listFiles(FileFilter) is another common SAM case:
/*
File(System.getProperty("user.home"))
.listFiles { file:File ->
Expand All @@ -32,12 +44,12 @@ object SAM {

}

// You can only do SAM conversions with Java interfaces.
// If you want to use a lambda when calling a Kotlin function, use first class functions.
// Type aliases can make this look nicer

}

// You can only do SAM conversions with Java interfaces.
// If you want to use a lambda when calling a Kotlin function, use first class functions.
// Type aliases can make this look nicer

typealias Handler = (Int)->Int

object TypeAliasExample {
Expand Down

0 comments on commit b63a154

Please sign in to comment.