首页 > 其他分享 >Kotlin Notes - 4

Kotlin Notes - 4

时间:2023-11-21 23:14:17浏览次数:23  
标签:function acc val Int Kotlin Notes fold lambda

  1. A higher-order function is a function that takes functions as parameters, or returns a function.

    fun <T, R> Collection<T>.fold(
        initial: R,
        combine: (acc: R, nextElement: T) -> R
    ): R {
        var accumulator: R = initial
        for (element: T in this) {
            accumulator = combine(accumulator, element)
        }
        return accumulator
    }
    

    To call fold, you need to pass an instance of the function type to it as an argument, and lambda expressions are widely used for this purpose at higher-order function call sites:

    val items = listOf(1, 2, 3, 4, 5)
    
    // Lambdas are code blocks enclosed in curly braces.
    items.fold(0, { 
        // When a lambda has parameters, they go first, followed by '->'
        acc: Int, i: Int -> 
        print("acc = $acc, i = $i, ") 
        val result = acc + i
        println("result = $result")
        // The last expression in a lambda is considered the return value:
        result
    })
    
    // Parameter types in a lambda are optional if they can be inferred:
    val joinedToString = items.fold("Elements:", { acc, i -> acc + " " + i })
    
    // Function references can also be used for higher-order function calls:
    val product = items.fold(1, Int::times)
    
  2. Kotlin uses function types, such as (Int) -> String, for declarations that deal with functions: val onClick: () -> Unit = ....

  3. The full syntactic form of lambda expressions is as follows:

    val sum: (Int, Int) -> Int = { x: Int, y: Int -> x + y }
    

    If you leave all the optional annotations out, what's left looks like this:

    val sum = { x: Int, y: Int -> x + y }
    
  4. According to Kotlin convention, if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses:

    val product = items.fold(1) { acc, e -> acc * e }
    

    If the lambda is the only argument in that call, the parentheses can be omitted entirely:

    run { println("...") }
    
  5. it: implicit name of a single parameter

    If the compiler can parse the signature without any parameters, the parameter does not need to be declared and -> can be omitted. The parameter will be implicitly declared under the name it:

    ints.filter { it > 0 } // this literal is of type '(it: Int) -> Boolean'
    
  6. You can explicitly return a value from the lambda using the qualified return syntax. Otherwise, the value of the last expression is implicitly returned.

    ints.filter {
        val shouldFilter = it > 0
        shouldFilter
    }
    
    ints.filter {
        val shouldFilter = it > 0
        return@filter shouldFilter
    }
    

标签:function,acc,val,Int,Kotlin,Notes,fold,lambda
From: https://www.cnblogs.com/otf-notes/p/17847850.html

相关文章

  • [题解]CF1899D Yarik and Musical Notes
    思路暴力化简公式题。假定\(b_{i}^{b_j}=b_{j}^{b_{i}}\)成立,那么有:\[2^{a_i\times2^{a_j}}=2^{a_j\times2^{a_i}}\\a_i\times2^{a_j}=a_j\times2^{a_i}\\\frac{a_i}{a_j}=\frac{2^{a_i}}{2^{a_j}}\\\frac{a_i}{a_j}=2^{a_i-a_j}\]因为\(\fra......
  • Kotlin Notes - 3
    Functionparameterscanhavedefaultvalues,whichareusedwhenyouskipthecorrespondingargument.Thisreducesthenumberofoverloads:funread(b:ByteArray,off:Int=0,len:Int=b.size,){/*...*/}Ifthelastargumentafterde......
  • 运用Kotlin开发Android应用的一些技巧
    今天的这篇文章带你学习使用Kotlin开发Android应用,并对比我们传统语言Java,让你真真切切的感受到他的美和优雅。配置项目gradle文件applyplugin:'com.android.application'applyplugin:'kotlin-android'applyplugin:'kotlin-android-extensions'dependencies{clas......
  • kotlin协程:一文搞懂各种概念
    前言使用kotlin协程已经几年了,可以说它极大地简化了多线程问题的复杂度,非常值得学习和掌握。此文介绍并梳理协程的相关概念:suspend、non-blocking、Scope、Job、CoroutineContext、Dispatchers和结构化并发。进入协程世界简而言之,协程是可以在其内部进行挂起操作的实例,是否支持......
  • Kotlin Notes - 2
    PropertiesinKotlinclassescanbedeclaredeitherasmutable,usingthevarkeyword,orasread-only,usingthevalkeyword.//fullsyntaxfordeclaringapropertyvar<propertyName>[:<PropertyType>][=<property_initializer>]......
  • kotlin 泛型基础
    一、泛型函数如下是泛型函数的一种构造在fun函数标记的右边增加该函数要使用的类型形参fun<T>List<T>.slice(indices:IntArray):List<T>{valret=mutableListOf<T>()for(vinindices){ret.add(this[v])}returnret}listOf(3,4,5,6......
  • Kotlin委托的深入解析与实践
    引言在Kotlin编程语言中,委托是一项强大的特性,它能够极大地简化代码,提高代码的可维护性。本文将深入探讨Kotlin中的委托机制,介绍其原理、具体使用方式以及实际应用场景。委托的原理委托是一种通过将实际工作委托给其他对象来实现代码重用的机制。在Kotlin中,委托通过关键字by来实现......
  • Kotlin Notes - 1
    AclassinKotlinhasaprimaryconstructorandpossiblyoneormoresecondaryconstructors.//primaryconstructorclassPerson(valname:String){valchildren:MutableList<Person>=mutableListOf()//secondaryconstructorconstru......
  • kotlin 内联函数 inline
    一、当函数被声明为内联函数(函数的前缀增加inline),那么函数体会被直接替换到函数被声明的地方,而不是被正常的调用。如下的代码inlinefunsynchronized(lock:Lock,action:()->Unit){lock.lock()try{returnaction()}finally{lock.unlo......
  • kotlin 高阶函数
    一、定义:以另一个函数作为参数或者返回值的函数1、kotlin中,函数以lambda或者函数引用来表示 二、函数类型1、如下是函数的类型上述声明了函数的类型,括号内包含了该函数类型需要传入的参数类型,紧接着箭头,最后是返回的类型(在声明函数类型时候,返回类型即使是Unit也不可以省略)......