Declaration and invocation of Kotlin classes and class methods, static methods, and local methods

package com.example.filetest

fun main() {
    functionLearn(121)//1. Call the method directly
    person(). test1() //2. call class method
    person. test2() //3. Call a static method of a class, also called a class method
    NumUtil.double(1) //4. Call the static method of the static class

* Define the method, fun is the keyword, functionLearn is the method name, days is the parameter name, Int is the parameter data type, Boolean is the return value data type
* */
fun function Learn(days: Int): Boolean {
    return days > 100

* Declaration class person
* */
class person {
    //Define the member methods of the class
    fun test1() {
        println("Member method")

    //Define the class method, that is, the static method of the class, the keyword companion is called Kotlin's companion object object
    companion object {
        fun test2() {
            println("implement class method")

// Declare the NumUtil tool class (static class) through the object keyword, and the methods in the class are all static methods
object NumUtil {
    // Declare a static method (as long as it is in the object class body, no other keyword modification is required) double, the function is to return the value of the parameter num multiplied by 2
    fun double(num: Int): Int {
        return num * 2

* Single expression method, when the method returns a single expression, you can omit the curly braces and specify the code body after the = sign
* fun double(x: Int): Int This part is the same as a regular statement
* = Mandatory connectors
* x * 2 is the return value
* */
fun double(x: Int): Int = x * 2
 * Define local methods (methods can also be added in the method body)
fun magic(): Int {
    fun foo(v: Int): Int {
        return v * v
//declare an integer variable v1, the value is a random number between 0-100
    val v1 = (0..100).random()
    return foo(v1 * v1)

Leave a Reply

Your email address will not be published. Required fields are marked *