如何在Kotlin中编写扩展函数?

我只是想将我的正常function转换为Kotlin的扩展function。

这是我的function,

fun hideKeyboard(activity: Activity) { if (activity != null) { activity.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_SATE_HIDDEN) val view: View = activity.currentFocus if (true) run { val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } } } 

你甚至可以用IDE提供的自动重构来完成这个工作:把光标放在你想要转换为接收器的参数上,按下Alt + Enter,然后选择Convert parameter to receiver

结果是:

 fun Activity.hideKeyboard() { if (this != null) { // Note: this check is redundant, since the type is not-null window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_SATE_HIDDEN) val view: View = currentFocus if (true) run { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } } }