android - 从其伴生对象扩展数据类的函数时不可见

标签 android kotlin

给定以下数据类:

data class Coords(val x: Int, val y: Int) {
    companion object CoordsOps {
        private val shiftTable: Map<Direction, Pair<Int, Int>> = mapOf(
            Direction.North to Pair(0, 1),
            Direction.East to Pair(1, 0),
            Direction.South to Pair(0, -1),
            Direction.West to Pair(-1, 0)
        )

        private operator fun Coords.plus(increment: Pair<Int, Int>): Coords =
            Coords(x + increment.first, y + increment.second)

        fun Coords.shift(direction: Direction): Coords = this + shiftTable.getValue(direction)
    }
}

我无法从该对象外部使用扩展函数shift()。我想使用Coords.shift(direction)

我做错了什么?

最佳答案

你应该可以。我完全复制了您的代码,并且能够从另一个文件调用扩展函数 shift。

也许您错过了导入?或者叫法不对?试试这个

import <your_package>.Coords.CoordsOps.shift

val y = Coords(3, 4).shift(Direction.East)

关于android - 从其伴生对象扩展数据类的函数时不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63984683/

相关文章:

android - ListView 中的两个可点击项目

android - 如何在 Kotlin 中处理后按

android - 无法从 ViewModel 向用户显示协程错误消息

android - 摩托罗拉 EMDK 实现 DataListener 崩溃 |安卓工作室

android - 如何将Android应用程序链接到服务器/计算机上的数据库?

android - 在 Recyclerview 中显示来自内部存储的图像

kotlin - 您可以在 Kotlin 中在运行时连接语句吗?

java - 如何在Java(Eclipse,android)中使用printstacktrace?

kotlin - GridView无法在Kotlin自定义日历中强制转换为ViewPager

kotlin - 在 build.gradle.kts 中设置环境变量