- Learn Kotlin Programming(Second Edition)
- Stephen Samuel Stefan Bocutiu
- 286字
- 2021-06-24 14:13:36
Extension function precedence
Extension functions cannot override functions declared in a class or interface. If an extension function is defined with the exact same signature (the same name, parameters type and order, and return type), then the compiler will never invoke it.
During compilation, when the compiler finds a function invocation, it will first look for a match in the member functions defined in the instance type as well as any member functions defined in superclasses and interfaces. If a match is found, then that member function is the one that is bound.
If no matching member functions are found, the compiler will consider any extension imports in the scope. Consider the following definitions:
class Submarine { fun fire(): Unit { println("Firing torpedoes") } fun submerge(): Unit { println("Submerging") } } fun Submarine.fire(): Unit { println("Fire on board!") } fun Submarine.submerge(depth: Int): Unit { println("Submerging to a depth of $depth fathoms") }
Here we have a Submarine type with two functions – fire() and submerge(). We have also defined extension functions on Submarine with the same names. If we were to invoke these functions, we would use the following code:
val sub = Submarine() sub.fire() sub.submerge()
The output would be Firing torpedoes and Submerging. The compiler will bind to the fire() function defined in the submarine class. In this example, the extension function can never be called, as there is no way to disambiguate it from the function in the class proper.
However, the submerge() function has different function signatures, so the compiler is able to bind to either depending on the number of parameters used:
val sub = Submarine() sub.submerge() sub.submerge(10)
This would output Submerging and Submerging to a depth of 10 fathoms.
- 從零開(kāi)始構(gòu)建企業(yè)級(jí)RAG系統(tǒng)
- MySQL數(shù)據(jù)庫(kù)管理實(shí)戰(zhàn)
- 跟老齊學(xué)Python:輕松入門(mén)
- Python編程與幾何圖形
- Spring快速入門(mén)
- Express Web Application Development
- 精通Python自動(dòng)化編程
- Learning Docker Networking
- Java EE企業(yè)級(jí)應(yīng)用開(kāi)發(fā)教程(Spring+Spring MVC+MyBatis)
- Xcode 6 Essentials
- 零基礎(chǔ)學(xué)C語(yǔ)言(升級(jí)版)
- 絕密原型檔案:看看專(zhuān)業(yè)產(chǎn)品經(jīng)理的原型是什么樣
- Implementing Domain:Specific Languages with Xtext and Xtend
- C/C++程序設(shè)計(jì)教程:面向?qū)ο蠓謨?cè)
- 微信小程序開(kāi)發(fā)零基礎(chǔ)入門(mén)