Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有什么方法可以实现像在kotlin中重写操作符这样的功能吗?_Kotlin - Fatal编程技术网

有什么方法可以实现像在kotlin中重写操作符这样的功能吗?

有什么方法可以实现像在kotlin中重写操作符这样的功能吗?,kotlin,Kotlin,最近,我在kotlin处理列表,有以下代码片段: a = listOf(1, 2, 3, 4) println(a[-2]) 当然,这会导致一个IndexOutOfBoundsException,所以我认为扩展这个功能会很好。因此我认为可以重写列表类中的get操作符: operator fun <T> List<T>.get(index: Int): T = // Here this should call the non-overridden vers

最近,我在kotlin处理列表,有以下代码片段:

a = listOf(1, 2, 3, 4)
println(a[-2])
当然,这会导致一个
IndexOutOfBoundsException
,所以我认为扩展这个功能会很好。因此我认为可以重写
列表
类中的
get
操作符:

operator fun <T> List<T>.get(index: Int): T =
        // Here this should call the non-overridden version of
        // get. 
        get(index % size)
操作员乐趣列表。获取(索引:Int):T= //在这里,这应该调用的非重写版本 //得到。 获取(索引%size) 我知道扩展只是静态方法,因此不能被重写,但是有没有一种方法可以实现这样的事情呢

当然,您可以创建另一个函数

fun <T> List<T>.safeGet(index: Int): T = get(index % size)
fun List.safeGet(索引:Int):T=get(索引%size)
但我想知道是否还有其他方法

(我知道,
index%size
是一种非常简单的方法,可以做我想做的事情,但这不是我问题的重点,它使代码变得更小。)

编辑


当我写这个问题时,我认为
%
操作符在右侧为正数时将始终返回正数,就像python中一样。我把原来的问题保留在这里只是为了保持一致性。

您正在尝试一些不可能的事情,因为扩展总是被成员跟踪,即使
@JvmName
也无法拯救您

解决方法:使用第二种解决方案,或添加一个丑陋的
Unit
参数(看起来像
a[x,Unit]
),但可以使用自己的
get
方法一起存在


另一种解决方案:创建自己的
列表
实现(推荐)。

由于
获取
运算符已在
列表
中定义,因此无法重新定义
获取
(使用一个
Int
参数)。 但是,您可以重写
invoke
运算符,该运算符未在
列表中定义

fun main(args: Array<String>) {
    val a = listOf(1, 2, 3, 4)
    println(a(-2))
}

// If `index` is negative, `index % size` will be non-positive by the definition of `rem` operator.
operator fun <T> List<T>.invoke(index: Int): T = if (index >= 0) get(index % size) else get((-index) % (-size))
fun main(args:Array){
val a=列表(1,2,3,4)
println(a(-2))
}
//如果'index'为负,'index%size'将根据'rem'运算符的定义为非正。
运算符fun List.invoke(索引:Int):T=if(索引>=0)get(索引%size)else get((-index)%(-size))
尽管我认为创建一个新的扩展方法来
列表
,使用一个合适的名称将是更可取的选择

作为旁注,
(正值)%(负值)
为非负值,
(负值)%(正值)
为非正值。

Kotlin中的
%
对应于Haskell中的
rem
,在下面的示例中:

好的,侧音让我吃惊。我没有料到。谢谢