kotlin 扩展类的功能
Function in programming means, a unit of code that performs a specific task. And they provide better modularity for your application and a high degree of code reusing. In Kotlin there are different function types and ways of use. I will try to explain about function in Kotlin in this writing.
编程中的功能是指执行特定任务的代码单元。 而且它们为您的应用程序提供了更好的模块化以及高度的代码重用性。 在Kotlin中,有不同的功能类型和使用方式。 我将在本文中尝试解释Kotlin中的函数。
You can start creating functions with keyword “fun” then you give a name, then parameter parenthesis and curly braces.
您可以使用关键字“ fun”开始创建函数,然后输入名称,参数括号和花括号。
fun takeSquare(number: Int): Int { return 2 * number }The section number: Int represents the parameter type, which means the number variable will be an Int type. If you try to assign a string or boolean value to number it will give an error. After the previous section “: Int” represents the return type. That means after calculation of the function it will return an Int value to the user. If you do not assign a return type, it will return the Unit type by default. Another part is the body of the function. In curly braces, you can develop your function for specific tasks.
段号:Int表示参数类型,这意味着number变量将是Int类型。 如果尝试将字符串或布尔值分配给number,则会出现错误。 在上一节之后,“ :Int”表示返回类型。 这意味着在计算函数之后,它将向用户返回一个Int值。 如果您未分配返回类型,则默认情况下它将返回单位类型。 另一部分是功能的主体。 在花括号中,您可以开发用于特定任务的功能。
Function usage
功能用法
If you want to call your function to use it you must call it in the main.
如果要调用函数以使用它,则必须在主体中调用它。
For example:
例如:
fun main() { takeSquare(2) val squareValue = takeSquare(2) Math.pow(2.0, 3.0) }On the 3. line you see the function call of the takeSquare. Parameter of the function requests Int number and you give that parameter inside the parenthesis. Also if there is a return value, you can assign it to a variable as in the 4. line. On the other hand, if you have a function inside a class you must use point “.” to call it. On the 7.line there is a built-in function called pow which takes the power of the first parameter.
在3.行上,您可以看到takeSquare的函数调用。 函数的参数要求输入Int编号,然后在括号内给出该参数。 另外,如果有返回值,则可以将其分配给变量,如4.行中所示。 另一方面,如果您在类内具有函数,则必须使用点“。” 称呼它。 在7.line上有一个内置的函数,称为pow ,它使用第一个参数的幂。
Default Arguments
默认参数
In Kotlin you can assign default values to parameters inside the parenthesis.
在Kotlin中,您可以为括号内的参数分配默认值。
fun reformatMessage(message: String, isUpperCase: Boolean = false, size: Int, lang: String = "tr") { }In the code sample, There are 4 parameters for the function. As you can see, isUpperCase parameter assigned as Boolean value and its default argument is “false”. The same case has occurred with lang parameter, the parameter type is String and the default argument is “tr”. When the function starts if the developer does not enter a value while function call, the function will be using these parameters to operate.
在代码示例中,该函数有4个参数。 如您所见, isUpperCase参数分配为布尔值,其默认参数为“ false”。 lang参数发生相同的情况,参数类型为String,默认参数为“ tr”。 如果开发人员在调用函数时未输入值,则函数启动时,函数将使用这些参数进行操作。
Named arguments
命名参数
For the same example above(code sample 2), there are 2 parameters with default arguments but also there are 2 parameters with no default argument. If you want to call that function you must assign values to those parameters with no default argument.
对于上面的同一示例(代码示例2),有2个参数带有默认参数,但也有2个参数没有默认参数。 如果要调用该函数,则必须为这些参数赋值,而没有默认参数。
reformatMessage("Message", true, 7, "tr") reformatMessage("Message", size = 7, lang = "tr") reformatMessage("Message", true, 7) reformatMessage("Message", size = 7)On the 3. line you see a function call and there is 4 value inside it. These values are a match for parameters of the function. message is “Message”, isUppercase is “true”, size is “7" and lang is “tr”. But on the 4. line there is 3 value and one is missing. In that case, you must name the arguments to assign them properly because the parameters are out of order. Normally there should be isUppercase in the second row but in 4. line there is the size in the second row and function is using the default value for isUppercase and we are stating that size will be ”7" and lang is “tr”.
在3.行上,您会看到一个函数调用,其中包含4个值。 这些值与函数的参数匹配。 message为“ Message”, isUppercase为“ true”, 大小为“ 7”, lang为“ tr”,但在第4行中,存在3个值,其中1个值丢失。通常,在第二行中应该有isUppercase ,但是在第4行中应该有isUppercase 。在第二行中有size ,函数使用的是isUppercase的默认值, 因此我们声明大小为” 7”,而lang是“ tr”。
Variable number of arguments
可变数量的参数
If you have many more parameters for the function you can define “vararg”(Variable number of arguments). The function can be assigned to a large number of variables while it seems to be taking a single parameter. And you can reach to these parameters as in the arrays with index[] or .get(index).
如果该函数还有更多参数,则可以定义“ vararg”(可变数量的参数)。 可以将函数分配给大量变量,而该函数似乎只有一个参数。 您可以使用index []或.get(index)到达数组中的这些参数。
fun bankAccountInfo(vararg userInfo: String, key: Int) { bankAccountInfo[3] bankAccountInfo.get(3) }You cannot use vararg more than once inside the function. When calling that function you should separate values with a comma and if you want to use an array for vararg you must use spread operator “*array” and that does not mean pointer as in the other C languages. Kotlin does not have pointers.
在函数内不能多次使用vararg 。 调用该函数时,应使用逗号分隔值,如果要为vararg使用数组,则必须使用扩展运算符“ * array ”,这并不意味着其他C语言中的指针。 Kotlin没有指针。
bankAccountInfo("caner", "Interstellar", "bursa", "Turkey", "", "", "", key = 3) bankAccountInfo(*arrayOf("caner", "Interstellar", "bursa", "Turkey"), key = 4)Single Expression Function
单表达功能
Usually, a function must declare its return type. But this is not valid for the functions that consist of a single expression. These are often called as one line or single-line functions. You have the option to shorten syntax with such functions. You can use = symbol before the expression rather than the return keyword.
通常,函数必须声明其返回类型。 但这对于包含单个表达式的函数无效。 这些通常称为单行或单行函数。 您可以选择使用此类功能来缩短语法。 您可以在表达式前使用=符号,而不要使用return关键字。
val userList = arrayOfNulls<String>(5) fun getListCount(): Int = userList.size fun pow(N: Int) = 8 * 2Infix functions make the functions look more organized. It replaces dot usage and there are some rules to create infix functions. First of all, it should start with the “infix” keyword. The function must be a member of another class or must be an extension function. It must be taking a single parameter and this cannot be “vararg”. And the infix function parameter cannot have a default value. Some of the infix ways of use below.
中缀函数使函数看起来更有条理。 它代替了点的用法,并且有一些规则可以创建中缀函数。 首先,它应该以“ infix”关键字开头。 该函数必须是另一个类的成员,或者必须是扩展函数。 它必须采用单个参数,并且不能为“ vararg”。 并且infix函数参数不能具有默认值。 以下一些infix使用方式。
if (!isStudent and isMale) { } //"and" is infix usage val awesomeInstance = AwesomeClass() awesomeInstance downloadImage "www.google.com.tr"Mathematical operators, type conversions, range usage has priority against infix functions. Also, infix functions have priority against logic operators(code sample 8).
数学运算符,类型转换,范围用法优先于infix函数。 此外,中缀函数相对于逻辑运算符(代码示例8)具有优先级。
val number = 5 if (number + number - 2 * (awesomeInstance specialPlus 4) == 5) { } if (number == 3 && number < 5 || awesomeInstance specialPlus 4 == 5) { }Local Functions
局部功能
In Kotlin, you can define a function inside a function. This is called Local Functions. The reason behind it, if you want to make this function unreachable, even from own class you can define a function inside a function.
在Kotlin中,您可以在函数内部定义函数。 这称为局部函数。 其背后的原因是,即使您想从自己的类中使该函数无法访问,也可以在函数内部定义一个函数。
fun calculateAtomPhysics() { val userName = "LetsCode!" println("Initialize Process...") fun getValuesFromUserAndPrint() { userName.length val numberOne = readLine()!!.toInt() val numberTwo = readLine()!!.toInt() val result = numberOne + numberTwo println("$result") } }Member Functions
会员职能
If your function is inside a class, that function called a member function.
如果您的函数在类内,则该函数称为成员函数。
class Car { fun setColor(colorCodeId: Int) { } }Generic Functions
通用功能
If a function takes a Generic Type, it is called a Generic Function.
如果函数采用通用类型,则称为通用函数。
fun <T> setColor(colorCodeId: T) { }Extension functions provide the ability to extend a class without having to inherit from the class or use design patterns. That means you can write new functions for a class that you can not modify. These new functions will not actually be part of the class.
扩展功能提供了扩展类的能力,而不必从类继承或使用设计模式。 这意味着您可以为无法修改的类编写新函数。 这些新功能实际上将不是该类的一部分。
fun log2(number: Number) { println(number) } infix fun Number.log(emptyParam: String) { println(emptyParam + this) } infix fun String.extPlus(otherString: String): Int = this.toInt() + otherString.toInt() fun main (){ "3" extPlus "" log "" "4" extPlus "" log "" 1235.log("") 5545454.log("") pi.log("") }If you have identical same method one inside a member class other one outside the class, it will compile the function inside the member class. But for example, if you change “edge: Int” to “edge: Double” (line 9) inside the function and call it with double value, it will compile the extension function (line 9).
如果在成员类内部使用相同的方法,而在类外部使用相同的方法,则它将在成员类内部编译函数。 但是例如,如果您在函数内部将“ edge:Int”更改为“ edge:Double”(第9行),并使用double值对其进行调用,它将编译扩展功能(第9行)。
class Shape { fun calculateArea(edge:Int): Int{ return edge * edge } fun calculateArea(edge: Int): Int = edge * edge } //*******************************************************// fun Shape.calculateArea(edge:Double): Int { val result = edge *edge println(result) return result }Functions are “First Class Citizen” in Kotlin. That means you can assign FCC’s to functions as a paramter or they can be a return value of a function.
功能是Kotlin中的“头等公民”。 这意味着您可以将FCC分配给函数作为参数,也可以将其作为函数的返回值。
Basically you can assign Higher Order Functions as parameters to a function.
基本上,您可以将高阶函数作为参数分配给函数。
fun foo(higherOrderFunction: (message: String) -> Unit){ higherOrderFunction("LetsCode!!") } fun main(){ foo({ message -> println("Message : $message") }) }You can define the Higher Order Function by assigning it to a variable. If you have more than one parameters you can order them by using comma before lamda arrow. If the Higher Order Function takes one parameter, you don’t have to write those parameters. In this case, the higher order function will give you a type that variable of the parameter named “it”.
您可以通过将其分配给变量来定义高阶函数。 如果您有多个参数,则可以在lamda箭头前使用逗号对它们进行排序。 如果高阶函数采用一个参数,则不必编写这些参数。 在这种情况下,高阶函数将为您提供一个名为“ it”的变量类型。
val higherOrderFunction = { surName: String -> "surName : $surName" } val anonymousFunction = fun(surName: String): String { return "surName : $surName" } val anonymousFunction2 = fun(surName: String): String = "surName : $surName"When defining parameters to the Higher Order Function, it can only be used by defining the variable type.
在定义高阶函数的参数时,只能通过定义变量类型来使用它。
The parameter must be called in the function after a higher order function is written as a parameter. Otherwise, it would be illogical to define this higher order function. This means that the body part of the higher order function in the field where the normal function is called will never be called
在将高阶函数作为参数写入后,必须在函数中调用参数。 否则,定义此高阶函数将是不合逻辑的。 这意味着在调用普通函数的字段中,高阶函数的主体部分将永远不会被调用
fun getItemClickListener(onClick: (String) -> Unit) { println("Click process is starting...") Timer().schedule(3000) { onClick("Login") println("Click process is over...") } }Thank you for reading my writing. I will write about android development in my next writings.
感谢您阅读我的文章。 我将在下一本书中撰写有关android开发的文章。
演示地址
翻译自: https://medium.com/swlh/functions-in-kotlin-c264bccd2847
kotlin 扩展类的功能