Kotlin series: function details, kotlin function details

Source: Internet
Author: User

Kotlin series: function details, kotlin function details

Summary: The Use and definition of functions in kotlin are more flexible and diverse. In addition, it supports different degrees of expansion to help developers create their own methods and improve development efficiency, here, we will briefly introduce the use of different functions. Extended functions will be introduced together with extended attributes in the next article.

Statement:

The function in Kotlin uses the fun keyword declaration:

fun double(x: Int): Int {    return 2 * x}
Function usage
Call a function using the traditional method:
val result = double(2)
Use the dot notation to call a member function:
Sample (). foo () // create a class Sample instance and call foo
Parameters

Function parameters are defined using Pascal notation, that isName:Type. Parameters are separated by commas. Each parameter must have an explicit type:

fun powerOf(number: Int, exponent: Int) {……}
Default parameters

Function parameters can have default values. If the corresponding parameters are omitted, the default values are used. Compared with other languages, this reduces the number of reloads:

fun read(b: Array
 
  , off: Int = 0, len: Int = b.size) {……}
 

The default value is defined by the = value after the type and the value given.

The override method always uses the same default parameter value as the base type method. When overwriting a method with a default parameter value, the default parameter value must be omitted from the signature:

Open class A {open fun foo (I: Int = 10 ){...... } Class B: A () {override fun foo (I: Int ){...... } // No Default Value}

If a default parameter is before a parameter without a default value, the default value can only be used by calling the function using the name parameter:

Fun foo (bar: Int = 0, baz: Int ){/*...... */} Foo (baz = 1) // use the default value bar = 0

If the last lambda expression parameter is passed out of brackets to the function call, the default parameter value is not allowed:

Fun foo (bar: Int = 0, baz: Int = 1, qux: ()-> Unit ){/*...... */} Foo (1) {println ("hello")} // use the default value baz = 1 foo {println ("hello ")}
When a function calls mixed location parameters and naming parameters, all location parameters must be placed before the first naming parameter. For example, you can call f (1, y = 2) but not f (x = 1, 2). Functions with Block Code bodies must always explicitly specify the return type.

Variable parameters

foo( string = *arrayOf("1","2"))//foo( "1","2")fun foo(vararg string: String){}
When a single expression is returned, a single expression function can omit curly braces and specify the code body after the = symbol:
fun double(x: Int): Int = x * 2
When the return value type can be inferred by the compiler, it is optional to explicitly declare the return type:
fun double(x: Int) = x * 2
Generic function functions can have generic parameters. You can specify them by using angle brackets before the function name. The following describes the generic parameters:
fun 
 
   singletonList(item: T): List
  
    {    // ……}
  
 
Function scopes in Kotlin can be declared at the top level of the file, which means you do not need to create a class like some languages such as Java, C #, or Scala to save a function. In addition to top-level functions, functions in Kotlin can also declare local scopes, as member functions, and extension functions. We create methods in the kotlin file separately without creating classes to get packages.
fun action(){ }

Local Functions

Create a twice () method in the add () method, and use the times of the external function in the twice () method to calculate the magnification:

fun add( a: Int ,  b:Int) : Int{        var  times = 2        fun twice() : Int{          val  c = a * times + b * times            Log.e("result====",c.toString())            return c        }        return  twice()    }
Call:

val result = add(2, 3)Log.e("result:", result.toString())
Output result:

02-07 11:55:52.019 14759-14759/com.example.administrator.kotlinpractise E/result====: 1002-07 11:55:52.019 14759-14759/com.example.administrator.kotlinpractise E/result:: 10
Member Functions

A member function is a function defined within a class or object:

Class Sample () {fun foo () {print (& Wear quot; Foo ")}}
Member functions are called in dot notation:

Sample().foo()


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.