简体   繁体   English

Kotlin 中的“ClassInstance.[Someclass::class.java]”是什么意思?

[英]What is the meaning of “ClassInstance.[Someclass::class.java]” in Kotlin?

I've seen people using ViewModelProvider[Someclass::class.java] instead of ViewModelProvider.get(Someclass::class.java), and it compiles in Android Studio.我见过有人使用 ViewModelProvider[Someclass::class.java] 而不是 ViewModelProvider.get(Someclass::class.java),它在 Android Studio 中编译。 The problem is that I couldn't find any documentation of such usage online.问题是我在网上找不到任何关于这种用法的文档。 例子

With kotlin you can add operator modifiers to your function.使用 kotlin,您可以将运算符修饰符添加到 function。 So if you have some class with a get function and you might want to access it with [] , like an array or map, you could add operator modifier.因此,如果您有一些 class 和get function 并且您可能希望使用[]访问它,例如数组或 map,您可以添加operator修饰符。

Square brackets are translated to calls to get and set with appropriate numbers of arguments.方括号被转换为使用适当数量的 arguments 获取和设置的调用。

So this only works for functions with name get or set !所以这只适用于名称为getset的函数!

class Provider {
  operator fun get(key: String)
  operator fun set(key: String, value: String) { ... }
}

Then you can call the function like:然后你可以像这样调用 function :

Provider().get("key") // IDE hint: should be replaced with indexing operator
Provider()["key"] // calls get()

Provider().set("key", "value") // IDE hint: should be replaced with indexing operator
Provider()["key"] = "value" // calls set()

Reference参考

Kotlin allows operator overloading by marking a function as an operator function. Kotlin 通过将 function 标记为operator function 来允许运算符重载。 The square brackets notation is one of these operators ( indexed access operator ).方括号表示法是这些运算符之一( 索引访问运算符)。

Kotlin automatically interprets Java functions as operator functions if their name and signature match the requirements of a Kotlin operator function . 如果 Kotlin 函数的名称和签名符合 Kotlin 运算符 ZC1C4145268E1ZA73 In this case, it interprets functions named get as an "indexed access operator" if they return something, which allows you to use square bracket notation.在这种情况下,如果名为get的函数返回某些内容,它将解释为“索引访问运算符”,这允许您使用方括号表示法。

ViewModelProvider[Someclass::class.java] is a shorter version of ViewModelProvider.get(Someclass::class.java) there is no differences. ViewModelProvider[Someclass::class.java]ViewModelProvider.get(Someclass::class.java)的较短版本,没有区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM