【发布时间】:2021-01-15 11:00:50
【问题描述】:
我知道在 kotlin 主页上有文档,但没有明确说明何时使用它,为什么这个函数需要一个接收器作为函数。创建内联函数的正确定义的正确方法是什么。
- 这是内联函数
inline fun String?.toDateString(rawDateFormat: String = MMMM_DD_YYYY, outputDate: String = MM_DD_YYYY, block: (date: String) -> String): String {
return try {
var sdf = SimpleDateFormat(rawDateFormat, Locale.US)
val date = sdf.parse(this.orEmpty())
sdf = SimpleDateFormat(outputDate, Locale.US)
block(sdf.format(date ?: Date()).orEmpty())
} catch (ex: Exception) {
block("")
}
}
- 我们也可以这样做
inline fun String?.toDateString(rawDateFormat: String = MMMM_DD_YYYY, outputDate: String = MM_DD_YYYY): String {
return try {
var sdf = SimpleDateFormat(rawDateFormat, Locale.US)
val date = sdf.parse(this.orEmpty())
sdf = SimpleDateFormat(outputDate, Locale.US)
sdf.format(date ?: Date()).orEmpty()
} catch (ex: Exception) {
""
}
}
如果有人可以对此有详细的解释?
编辑:
我了解内联函数会在编译器调用时插入代码。但这引起了我的注意,当我想使用没有功能参数接收器类型的内联函数时,警告显示为 this 应该有更好的解释。我也想了解为什么会有这样的建议。
【问题讨论】: