如何在伴随对象中使用扩展函数

How to use an extension function in a companion object

是否可以在 class' 伴随对象中定义和使用扩展函数?

在此示例中,removePadding()Point.parse() 中使用的扩展函数。

data class Point(private var x: Int, private var y: Int) {
    companion object {
        fun parse(text: String?) = text?.removePadding()
            ?.let { "(\d+),(\d+)".toRegex().find(it) }
            ?.mapNotNull { it.toIntOrNull() }
            ?.let { Point(it[0], it[1]) }

        // define removePadding() here?
    }

    // define removePadding() here?
}

扩展函数 removePadding() 可能如下所示:

fun String.removePadding() = this.replace("\s+".toRegex(), "")

并且 parse 函数可以调用为:

val one = Point.parse("1, 7")

如果可能,怎么做?如果不是,为什么不呢?

因为你只需要函数作为 parse 的助手,你应该在它旁边声明它。

companion object {
    private fun String.removeWhitespace() = replace("\s+".toRegex(), "")

    fun parse(text: String?): Point? {
        ...

您基本上可以将扩展名放在任何这些地方,正常声明它:

private fun String.removePadding() = this.replace("\s+".toRegex(), "")

private 修饰符限制对伴随对象或 data class 的可见性,具体取决于您放置它的位置。通常,人们应该更喜欢声明的尽可能窄的可见范围。

另一种选择是在 parse 函数中本地声明扩展函数(注意这次它没有可见性修饰符):

data class Point(private var x: Int, private var y: Int) {
    companion object {
        fun parse(text: String?): Point? {
            fun String.removePadding() = this.replace("\s+".toRegex(), "")

            return text?.removePadding()
                ?.let { "(\d+),(\d+)".toRegex().find(it) }
                ?.groupValues?.map { it.toIntOrNull() ?: return null }
                ?.let { (x, y) -> Point(x, y) }
        }
    }
}