为什么Kotlin无法覆盖List< *>运算符方法? [英] Why Kotlin can not override List<*> operator method?

查看:131
本文介绍了为什么Kotlin无法覆盖List< *>运算符方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的职能:

operator  infix fun  List<Teacher>.get(int: Int): Teacher {
    var t = Teacher()
    t.name = "asd"
    return t ;
}

和我的用法:

b[0].teachers[1].name

提示:b是具有List<老师>财产

tip: b is an object that has List< Teacher > property

和错误Empty list doesn't contain element at index 1.

为什么此替代运算符功能不起作用?

why this override operator function doesn't work?

推荐答案

在Kotlin中,您不能隐藏带有扩展名的成员函数. 成员始终会在通话解决方案中获胜.因此,您基本上不能调用具有与成员函数相同的签名的扩展名,该扩展名存在于为表达式声明或推断的类型中.

In Kotlin, you cannot shadow a member function with an extension. A member always wins in the call resolution. So, you basically cannot call an extension with a signature same to that of a member function, that is present in the type that was declared or inferred for the expression.

class C {
    fun foo() { println("member") }
}

fun C.foo() { println("extension") }

C().foo() // prints "member"

在您的情况下,成员函数为kotlin.collections.List中定义的abstract operator fun get(index: Int): E .

In your case, the member function is abstract operator fun get(index: Int): E defined in kotlin.collections.List.

请参见语言参考:扩展名已解析静态

See the language reference: Extensions are resolved statically

这篇关于为什么Kotlin无法覆盖List&lt; *&gt;运算符方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆