gpt4 book ai didi

java - 为什么这个类型需要显式强制转换?

转载 作者:行者123 更新时间:2023-11-30 03:09:15 25 4
gpt4 key购买 nike

我为 JavaFX TableColumn 创建了一个扩展函数,可以更简洁地实现 cellFactory,而无需重复的样板文件。扩展函数定义如下:

inline fun <S, T> TableColumn<S, T>.cellFormat(crossinline formatter: (TableCell<S, T>.(T) -> Unit)) {
cellFactory = Callback { column: TableColumn<S, T> ->
object : TableCell<S, T>() {
override fun updateItem(item: T, empty: Boolean) {
super.updateItem(item, empty)

if (item == null || empty) {
text = null
graphic = null
} else {
formatter(this, item)
}
}
}
}
}

要格式化 TableCell,我只需要定义当前单元格有非空项可用时 TableCell.updateItem 中应该发生的情况。例如,要格式化 LocalDateTime,我现在可以编写:

column.cellFormat { text = DateTimeFormatter.ISO_DATE_TIME.format(it) }

然后我继续定义另一个扩展来执行此操作,因此我可以编写:

column.formatAsDateTime()

该函数使用第一个函数,如下所示:

fun <S, LocalDateTime> TableColumn<S, LocalDateTime>.formatAsDateTime() =
cellFormat { value ->
text = DateTimeFormatter.ISO_DATE_TIME.format(value as TemporalAccessor)
}

我的问题是为什么我必须将 LocalDateTime 转换为 TemporalAccessor?

我的第一次尝试是:

text = DateTimeFormatter.ISO_DATE_TIME.format(value)

编译器提示:

Type mismatch: inferred type is LocalDateTime but java.time.TemporalAccessor! was expected

当然,DateTimeFormatter#format 函数采用 TemporalAccessor,而不是 LocalDateTime,但 LocalDateTime 确实实现了 TemporalAccessor(通过 Temporal)。

仅在 formatAsDateTime 扩展函数中才需要转换为 TemporalAccessor,而直接从调用站点使用 cellFormat 时则不需要。

Kotlin 不应该能够自动执行此智能转换吗?

最佳答案

刚刚弄清楚,新手错误。 LocalDateTime 类型参数只是一个别名。正确的声明是:

fun <S> TableColumn<S, LocalDateTime>.formatAsDateTime() =
cellFormat { text = dateTimeFormatter.format(it) }

关于java - 为什么这个类型需要显式强制转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33976196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com