当前位置:网站首页>Kotlin advanced
Kotlin advanced
2022-07-24 10:11:00 【Deciduous ex】
Kotlin Advanced
Set creation
Kotlin There is no set of its own API It's called directly Java The original set , This has two advantages , One : Yes Kotlin Developers don't have to go ” Repeat the wheel “; Two : For users , Saved learning costs .
Common set
- We know that Java Initializing a collection in is usually divided into two steps : establish , assignment . At first glance, there is nothing wrong , But it will be troublesome when we want to create a known fixed set , Because you can't assign values to a set at the same time as an array .Kotlin This operation is optimized in , So that we can create an array initialization A set with default values .
//Java List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); //Kotlin val list = listOf(1,2,3)Key value pair set
- So for a set containing key value pairs , Such as :map. It also provides a more convenient way to write .
val map = mapOf(1 to "one",2 to "two",3 to "three")- adopt
toYou can directly generate aPairobject , That is, the key value pair object . ad locumtoIt is not a special structure , It's calledInfix functionNormal function of , Infix functions will be introduced in detail later .
Infix function
Ordinary functions are used through object . Function name Realized , stay kotlin In order to facilitate our use, another function type is introduced —— Infix function . This function passes infix Keyword definition , There is and only one parameter , By placing object Then use it directly , The function name is followed by the value passed in by the function . There is no need to . or () And other special symbolic links .
// Infix function
infix fun String.getChar(position: Int) = this.get(position)
val s = "Hello world"
val c = s getChar 1
// Ordinary function
fun String.getChar(position: Int) = this.get(position)
val s = "Hello world"
val c = s.getChar(1)Top level functions and properties
Java Zhongyingin ” All things are objects “ Design principle of , All functions and attributes are attached to class To achieve , Therefore, we have to create a class for many independent tool methods to manage , That's what we often say Tool class . Such an implementation is actually a little strange , But in Kotlin Programming solves such troubles for us .
Top level function
- We can do it in any ordinary
.ktThe file declares the function we want , And we don't need to create wrapper classes for this function , This function is the function itself ( It's a bit awkward. ), Just with us C The language is the same , Take function as basic unit instead of class .
package com.example.xxx.kotlinapplication fun log(message: String?) { Log.i("TAG", message) }- Do you feel comfortable both physically and mentally , But in fact, it will eventually compile into Java Bytecode , So the implementation code is actually like this :
package com.example.xxx.kotlinapplication public class XXX() { public static void log(String message) {Log.i("TAG", message)} }- See here, you may find , In fact, from the implementation principle, the top-level function is just convenient for our programmers to write , In fact, it is the same as ordinary static methods .
- We can do it in any ordinary
The top attributes
- Similar to the top-level function , Can be used to store some fixed
URLwait .
- Similar to the top-level function , Can be used to store some fixed
Expand functions and properties
stay Java in ” All things are objects “ Under the thought of , All functions and attributes are based on class There is , But many classes are made up of JDK Or sealed by others , At this time, if we need to expand it, we must extend, This undoubtedly increases the complexity and coupling of our architecture . In order to solve this situation ,kotlin The concepts of extended functions and attributes are introduced .
Extension function
As kotlin A major feature of , The extension function can be in whatever The place is There are classes Expand the function , Expanded function The use method is consistent with the original sound function method .
With our most common
ToastFor example , Generate a Toast We need to pass in at least three parameters , The most important thing isContextContext object , Because the creation of windows needs to be based on context , So we usually need to write a Toast Tools to facilitate our use , But with the extension function, you can find anyContextDirectly call our extended methods under subclasses .
// Define the extension function fun Context.toast(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() } // Click monitor fun onclick(){ toast(" Click. ") }Extended attribute
- Similar to the expansion function , You can extend attributes for existing classes , And properties can also be set to their specific
setterandgetterOf .
var StringBuilder.lastChar: Char get() = get(length - 1) set(value) { this.setCharAt(length - 1, value) } val name = StringBuilder("name") name.lastChar = 'o' log("lastChar:${name.lastChar} name:$name") Print the results :lastChar:o name:namo- Similar to the expansion function , You can extend attributes for existing classes , And properties can also be set to their specific
Be careful
actually ” expand “ The principle of is to declare the corresponding static attributes and functions , For example, the extension function is to declare a static function and then pass the extension object as a parameter .
therefore , Extended functions cannot be rewritten , To be specific, the expanded function is not satisfied
polymorphicPrinciple . for example :
open class Father class Son : Father() fun Father.onClick() { log("I'm Father") } fun Son.onClick() { log("I'm Son") } // Initialize two Son object val father: Father = Son() val son: Son = Son() // call father.onClick() son.onClick() // Output results : //father: I'm Father //son: I'm Son- Above , If according to our object-oriented
Richter's principle of substitution, Both objects are actually Son The object of , Only one is through the reference of the parent class to , The other is the reference of the class itself , Therefore, the output results should be ”I’m Son“. But because the extension function is based on static function , So it doesn't conform to the rules of object-oriented . In short, it is , it No matter what object is finally generated , It only cares about What object does the system recognize , That is, it will followquoteTo call .
Local extension function
The most direct way to evaluate a piece of code is to see whether it has duplicate code . But in our normal coding , We often encounter repeated small pieces of code in a small function , Encapsulating this code as a method will make the whole project ( class ) Become bloated , It reduces the readability and simplicity of the code . stay Kotlin There can be more elegant solutions in , Is the local extension function .
In plain terms, the local extension function is : You can define functions in functions , And call .
The general usage is similar to the inner class , You can define an internal function directly in a function , Internal functions can also be defined in internal functions , And the internal function can only be called internally , Unlike inner classes, which can be called separately elsewhere .
At the same time, internal functions can be accessed directly like internal classes Its subordinate functions can access All parameters and variables of .
as follows :
val User(name:String,address:String) fun (user:User){ if(user.name.isEmpty){user.name = " anonymous "} if(user.address.isEmpty){user.address = " Unknown "} } // Use local expansion functions val User(name:String,address:String) fun (user:User){ fun validate(value:String,hint:String){ if(value.isEmpty){value = hint} } validate(user.name," anonymous ") validate(user.address," Unknown ") }
Function default
stay Java Many parameters with the same name need to be written in because the number of parameters that a function needs to pass in is different , That is, the method we are familiar with heavy load . If our parameters can be set to default values , And you can choose how many words are passed in , You can save a lot of overloaded methods .
stay Kotlin In the function rule of , You can set a default value for each parameter , When this parameter is not passed in, the function will be compiled with the default value .
You must follow the Defined parameter order To give parameters , Sure Omit Only in At the end of Parameters of .
fun addUser(name: String = " unknown ", age: Int = 100, sex: Char = ' male ', id: Int = -1) {} addUser() addUser(" Zhang San ") addUser(" Li Si ", 10) addUser(" Wang Wu ", 10, ' male ', 1)If you use
Named parametersYou can specify any parameters you want to set .addUser(age = 5, id = 10) addUser(" Zhao Liu ",sex = ' demon ')
Named parameters
When we look at their code and the code we wrote before , We often encounter such problems , That is, I don't know what the parameters passed in by a function are , In this case, we can only click in to check the details of the method . Naming entries can help us friendly optimize such problems .
Named parameters can explicitly write out the parameter names and corresponding values we pass in when we call a method , This can improve the readability of our code .
fun test(key:Int,value:String) test(key = 1,value = "one")But in fact
Android StudioThe editor in has implemented similar functions for us , It allows us to directly see the naming of the corresponding function parameters when reading the code .Since the editor has been able to achieve the effect of optimizing reading , Then why introduce named parameters ? In fact, I didn't know before , I just think this is a chicken rib function , Until I learned the usage of function default value , Above , When using function defaults , Originally, parameters can only be passed in and defaulted through parameter order , But with named parameters, you can completely ignore the parameter position , Assign directly to any parameter you want .
fun addUser(name: String = " unknown ", age: Int = 100, sex: Char = ' male ', id: Int = -1) {} addUser(age = 5, id = 10) addUser(" Zhao Liu ",sex = ' demon ')
边栏推荐
- This article takes you to understand the dynamic memory allocation of C language
- Web page opening speed is very slow, how to solve it?
- cannot unpack non-iterable NoneType object
- Spark Learning: how to choose different association forms and mechanisms?
- [STM32 learning] (18) STM32 realizes LCD12864 display - parallel implementation of 8-bit bus
- 757. Set the intersection size to at least 2: greedy application question
- How does ribbon get the default zoneawareloadbalancer?
- Friends come to interview a unicorn company in Beijing at leisure. The interview question is priced at 25K
- Can the "self-help master" who has survived the economic crisis twice continue to laugh this time?
- Analysis of Kube proxy IPVS mode
猜你喜欢

程序的编译与链接

Write a simple memo using localstorage

Analysis of Kube proxy IPVS mode

Homologous policy solutions

缓冲区的概念真的理解么?带你揭开缓冲区的面纱~

Dark king | analysis of zego low illumination image enhancement technology

The heads of the five major international institutions called for urgent action to deal with the global food security crisis

Spark Learning: using RDD API to implement inverted index

Openstack network neutron knowledge point "openstack"

What did zoneawareloadbalancer of ribbon and its parent class do?
随机推荐
Linux deployment mysql8.0
[STM32 learning] (10) stm32f1 general timer realizes pulse counter
How does ribbon get the default zoneawareloadbalancer?
07 Jason module
Raspberry Pie: /bin/sh: 1: bison: not found
Websocket 协议解读-RFC6455
Synchronized scope "concurrent programming"
JS bind simulation
How to solve the problem of robot positioning and navigation in large indoor scenes with low-cost solutions?
Raspberry Pie: [failed] failed to start /etc/rc local Compatibility.
The best time to buy and sell stocks (leetcode-121)
In the envy of LETV, there is a "meaning crisis" of contemporary workers
Uniapp calendar component
Sub query of multi table query_ Single row and single column
Calculate CPU utilization [Prometheus]
Gaode map
[STM32 learning] (18) STM32 realizes LCD12864 display - parallel implementation of 8-bit bus
Notes on using setupproxy
聚集日志服务器
error: field ‘XXX’ declared as a function