Functions in the Kotlin

Source: Internet
Author: User
Tags anonymous closure cos eval modifier

No matter the function or the method we collectively refer to the function here, the function in Koltin is much richer than that in Java, we have this article to understand the various functions in Kotlin. Inline Functions

Android Development, printing information in general we will use the log class, log each method we have to pass two parameters, the first tag parameter in the Kotlin we can be encapsulated as below, so that only one parameter must be passed.

Inline Fun <reified t> t.debug (log:any)
{
    log.d (T::class.simplename, log.tostring ())
}

We find that it can get to the concrete type of t through the generic parameter T, and get its class name--and, of course, you can even call its constructor to construct an object if you want to--why Kotlin can do it. Because this code is inline, the final compile time is to compile to call it in the code block, when the type of T is actually determined, so Kotlin through reified this keyword to tell the compiler, T this parameter is not just a device, I want to use it as the actual type. single-expression functions

If the function body of a function has only one expression, the function body can be written directly after "=", that is:

Fun double (x:int): Int = x * 2

Again such as the following:

Fun eval (expr:expr): Double = if (expr) {is
    expr.const, Expr.number is
    expr.sum, eval (expr.e1) + eval (EXPR.E2)
    Expr.notanumber-Double.NaN
    //the ' Else ' clause is not required because we ' ve covered all the cases
}

The When keyword is used here, similar to switch in Java, but more powerful. Anonymous Functions

/**
 * Anonymous function, no name, other syntax and regular functions like
 *
 * Declare an anonymous function, where the function body is represented by an expression, that is, the single expression function
 *
/var test3= fun (X:int,y:int ): Int=x+y
/**
 * Declares an anonymous function, where a block of code is used to represent the function body
 *
/var test4= fun (x:int,y:int): Int {
    return  x+ Y
}
/**
 * Declares an anonymous function that, when the return value type can be inferred, can be omitted
 *
/var test5= fun (x:int,y:int) =x+y fun

main (args : array<string>) {

    println (test3)
    println (test4)
    println (TEST5)
}
higher-order functions and lambda expressions

Higher-order functions are functions that can accept functions as arguments or return a function. For example, lock () is a good example.

Fun lock<t> (Lock:lock, Body: () t): t {
    lock.lock ()
    try {
        return body ()
    }
    finally {
  
   lock.unlock ()
    }
}
  

In Kotlin and many similar languages have a convention, that is, if the last argument is a function, it can be defined outside the parentheses:

Val result = Lock (lock, {sharedresource.operation ()})
//is equivalent to
Lock (lock) {
    sharedresource.operation ()
}

A lambda expression is a simple form of defining an anonymous function, and what is the difference between a lambda expression and an anonymous function: whether the type of the return value is specified

The type of the lambda expression return value is obtained by automatic inference
The return value type of the anonymous function must be specified manually, and if the return value type is not specified, the default return value type is unit return behavior

The return in the lambda expression will be returned from the function containing the lambda expression
Return within an anonymous function will only return the recursive function from the anonymous function itself

What is tail recursion. Tail recursion is the line of code that is called recursively, which is the last line of code for the function. In Koltin, the tail recursion is optimized, and the function using Tailrec modifier is called tail recursive function to avoid the risk of memory overflow.

Tailrec Fun Findfixpoint (x:double = 1.0): Double 
    

This code calculates the mathematical cosine of the fixed point. Math.Cos is repeated from 1.0 until the value is unchanged, and the result is 0.7390851332151607 this code is equivalent to the following:

Private Fun Findfixpoint (): Double {
    var x = 1.0 While
    (true) {
        val y = math.cos (x)
        if (x = = y) return y
        x = y
    }
}

In fact, the recursive invocation of a function is replaced by a while iterative method. Local Functions

A local function is an inner function defined in the body of a function.

Fun DFS (graph:graph) {Fun
    dfs (Current:vertex, visited:set<vertex>) {
        if (!visited.add (current)) return For
        (v
            -in current.neighbors) Dfs (V, visited)
    } 

    dfs (Graph.vertices[0], HashSet ())
}

Local functions can access local variables in external functions, so in the example above, visited can be defined as a local variable. Static Methods

There are two ways companion object associated objects correspond to classes, one class with only one associated object

Class Main2activity:appcompatactivity () {

    override fun OnCreate (Savedinstancestate:bundle?) {
        super.oncreate (savedinstancestate)
        Setcontentview (r.layout.activity_main2)
    }

    Companion Object {Fun

        getstatic () {

        }

        getstaticstring (string:string): string? {
            return null
        }
    }
}
Object declares a special class using the Object keyword, which has only one instance, so it looks as if the entire class is an object.
Object Moreimageutils {fun
    filestomultipartbodyparts (files:list<file>): list<multipartbody.part> ? {
        return null;
    }
}

In this case, the class keyword is changed to object, and the members of this class are static by default. top-level functions

In Kotlin, functions can be defined as Top_level, which is the function under the package. Functions are defined in different ways, and their scopes are not the same. Of course, the scope of the function is also related to modifiers.

File Name:example.kt
package foo
private Fun foo () {}///Only accessible within Example.kt file
internal val baz = 6//In the same The module can access the Fun
Testfun () {}//default modifier public, which is decorated in any location
extension Functions

Kotlin's extended function allows us to add new functions to existing classes to implement a specific function.
Extension functions are statically parsed and do not add functions or properties to the original class, and have no effect on the class itself.

Fun Activity.toast (message:charsequence, duration:int = toast.length_short) {
    Toast.maketext (this, message, Duration). Show ()
}
Public inline Fun <t, r> t.let (block: (T)-R): R = Block (this)

Kotlin provides some extension functions and top-level functions. Let function

Let defaults to the current object as the IT parameter of the closure, the return value is the last line inside the function, or the specified return

Fun Testlet (): Int {
    //fun <t, r> T.let (f: (T)-R): R {F (This)}
    ' Testlet '. Let {
        println (IT)
        println (IT)
        println (IT)
        return 1
    }
}
Apply function

Call the Apply function of an object, and within the scope of the function, you can call any method of the object and return the object.

Arraylist<string> (). Apply {
    Add ("testapply")
    Add ("testapply")
    Add ("testapply")
    println (" this = "+ this"
}.let {println (IT)}

//Run result
//this = [Testapply, testapply, testapply]
//[Testapply, Testapply, Testapply]
with function

The WITH function returns the last line, and can then invoke the object's method directly, feeling like a combination of let and apply.

Fun Testwith () {
    //fun <t, r> with (Receiver:t, F:t. () R): R = Receiver.f () with
    (Arraylist<strin G> ()) {Add ("Testwith") Add ("
        testwith") Add ("
        testwith")
        println ("this =" + this)
    }.let {println (IT)}
}
Run result
//this = [Testwith, Testwith, Testwith]
//Kotlin. Unit
Run

The run function is much like the Apply function, except that the run function uses the return of the last line, and apply returns the current object.

Fun TestRun () {
    //fun <t, r> T.run (f:t. () R): R = f ()
    "TestRun". Run {
        println (' this = ' + this) C3/>}.let {println (IT)}
}
//Run result
//this = TestRun
//Kotlin. Unit
Repeat

There is nothing to say, repeat doing something, his source code is as follows:

@kotlin. internal.inlineonly public
Inline Repeat (Times:int, action: (INT)-Unit) {for
    (index in 0..tim ES-1) {
        Action (index)
    }
}
Lazy

Lazy delay operation, when first accessed, invokes the corresponding initialization function, for example:

Fun Readfromdb (): String = ...
Val lazystring = lazy {readfromdb ()}

val string = Lazystring.value

The lazy closure is called when the lazystring is first used. Generally used in single-case mode. Use

Use is used on try-with-resources expressions on Java, for example:

Val input = Files.newinputstream (Paths.get ("Input.txt"))
val byte = Input.use ({input.read ()})

Use will close the input anyway, avoiding writing complex try-catch-finally code.

The last small example:

Val long = 100L
val db2 = 100.db

//Extended attribute
private Val  Int.db:BigDecimal
    get () = BigDecimal (this)


Data class Money (Val Amount:bigdecimal, Val currency:string)
//Operator overloading
operator Fun Money.plus (Money:money) =
  if (currency = = money.currency)
        {Money
            (amount+money.amount, currency)
        }else {
            throw IllegalArgumentException ("We ' re has a problem here!")
        }

Any extension function with a single argument can use the infix character
infix fun int.percentof (Money:money) = Money.amount.multiply (BigDecimal (this)). Divide (BigDecimal (+))

Fun Main (args:array<string>) {

    val res = 7.percentOf (Money (3.db, "$"))

    //Infix call
    7 Percentof Money ( 2.db, "$")

    println (res)

    val costs = Money (100.db, "$"). Plus (Money (200.db, "$"))
    println (Costs.amount)

}

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.