owner of kotlin member function

Kotlin can obtain information about the owner of the function and the bound object. Suppose there are the following two classes:

 

class A(){
       fun fa(){}
 }
 class B: A()

val KFunction<*>.ownerClass: KClass<*> get() {       
        return (this as FunctionReference).owner as KClass<*>
}

 The owner type can be obtained through KFunction.ownerClass, and the following is the test result:

A::fa.ownerClass => A::class
 A()::fa.ownerClass => A::class
 B::fa.ownerClass => B::class
 B()::fa.ownerClass => B::class

This is useful in web development, assuming a class is a controller

class PersoController:Controller(){
        fun listAction(){
        }
}

The redirected function can be written like this

redirect(PersonController::listAction)

 Why not just use a string? For example: redirect("person/list"). 

Strings are easy to fall off when refactoring, reducing the chance of making mistakes is improving efficiency. 

Symbols are also commonly used in Ruby to replace strings.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326236685&siteId=291194637