官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 丹东市| 福贡县| 华坪县| 蓬安县| 神木县| 建湖县| 万年县| 沭阳县| 潼南县| 凌源市| 云龙县| 高唐县| 宁陵县| 平陆县| 怀化市| 隆德县| 日照市| 福泉市| 绥德县| 巫山县| 宁城县| 合水县| 周宁县| 丰城市| 屏南县| 建平县| 安新县| 浦江县| 延吉市| 定州市| 迭部县| 蓬安县| 绩溪县| 公主岭市| 华蓥市| 临湘市| 曲麻莱县| 饶平县| 广水市| 赤水市| 科技|