Kotlin ใช้ Java ดังนั้นเราจึงสามารถใช้ฟังก์ชันไลบรารีที่ใช้ Java เพื่อชะลอการเรียกใช้ฟังก์ชันได้ ในบทความนี้ เราจะใช้ฟังก์ชันไลบรารี Java เพื่อชะลอการเรียกใช้ฟังก์ชันโดยใช้ Timer() และ schedule() .
ตัวอย่าง
import java.util.Timer
import kotlin.concurrent.schedule
fun main(args: Array<String>) {
// Execution starting point
println("Hello world!!")
// Delay of 5 sec
Timer().schedule(5000){
//calling a function
newMethod()
}
}
fun newMethod(){
println("Delayed method call!")
} ผลลัพธ์
เมื่อดำเนินการแล้ว ส่วนโค้ดด้านบนจะให้ผลลัพธ์ต่อไปนี้ -
Hello world!! Delayed method call!