The Bug that can’t be changed, the pretense that can’t be written. The public account Yang Zhengyou now focuses on the development of mobile basic platform, covering various knowledge fields such as audio and video, APM and information security. Only do the whole network the most Geek public number, welcome your attention! Wonderful content should not be missed ~
I. Introduction to Kotlin
Kotlin has a strong ecosystem because it is a functional language that runs on the Java virtual machine and fully conforms to the DESIGN specifications of the JVM, such as type erasure, boxing and unboxing, etc. So it’s possible to support Android native development, server, and even the big front end just like Java. So what do Kotlin and Java have in common?
Similarities between Kotlin and Java8
I summarize three similarities between Kotlin and Java8: they are both object-oriented and functional programming languages, they are both strongly typed static languages, and they both conform to JVM design specifications
Let’s talk about their differences
Differences between Kotlin and Java8
There are many differences between Kotlin and Java8, so I can summarize them briefly:
- Kotlin can use the operator to render a short null
- Kotlin doesn’t need findViewById
- Kotlin gives you setter and getter methods by default
- Kotlin drops the static keyword
- Kotlin does automatic casting
- Kotlin does away with type inference
- Kotlin does not support type checking
- Kotlin has coroutine support
Kotlin and Java interweave
4.1 turn kotlin Java
In the navigation bar, right-click -> Tools -> Kotlin -> Show Kotlin Bytecode -> Decompile
4.2 Java kotlin
Select the File label: right-click -> Convert Java File To Kotlin File
Check out the Kotlin bytecode
5. Kotlin basic grammar
5.1 kotlin method
5.1.1 Kotlin method declaration
Kotlin defines the parameters in simple brackets in the format: “function name (parameter name: parameter): return type”. The return type is defined outside the brackets as T
fun <T> reflectField(instance: Any? , name:String): T? {
if (instance == null) return null
try {
val field = instance.javaClass.getDeclaredField(name)
field.isAccessible = true
return field.get(instance) as T
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
Copy the code
5.1.2 Kotlin method call
5.1.3 Kotlin method automatically sends parameters
Kotlin can set the default arguments in the constructor or related function parentheses, so that the default arguments can be used for passing arguments
The second argument can be omitted and the default value will be used It’s just like Java when you don’t omit it
5.1.4 ensuring kotlin named argument
Named argument: You can pass arguments according to their names, not in the order defined by the function. In this way, you can avoid parameter mistransmission
5.2 Kotlin variables and constants
Varible is declared by the var keyword, in the form of var variable name [: type] = [initial value]
private var mConfig = RabbitConfig()
lateinit var application: Application
private var isInit = false
Copy the code
- The variable declared by val is read-only and its reference cannot be changed; in fact, we can still change the mutable member of the object referenced in it
- Const is equivalent to final in Java, meaning that once initialized, it is immediately visible to main memory and cannot be assigned twice
Of course, Kotlin also has automatic unboxing and boxing to translate Int into Java Int or Integer to improve performance
private var Int = 8
Copy the code
Kotlin automatically adds setter and getter methods to properties
class RabbitConfig(
var enable: Boolean = true.var enableLog: Boolean = true.@Transient var uiConfig: RabbitUiConfig = RabbitUiConfig(),
var storageConfig: RabbitStorageConfig = RabbitStorageConfig(),
var monitorConfig: RabbitMonitorConfig = RabbitMonitorConfig(),
var reportConfig: RabbitReportConfig = RabbitReportConfig()
)
Copy the code
Show Kotlin Bytecode
If you want to override the set() or get() methods, you can do so
data class RabbitConfig(
var enable: Boolean = true.var enableLog: Boolean = true.@Transient var uiConfig: RabbitUiConfig = RabbitUiConfig(),
var storageConfig: RabbitStorageConfig = RabbitStorageConfig(),
var monitorConfig: RabbitMonitorConfig = RabbitMonitorConfig(),
var reportConfig: RabbitReportConfig = RabbitReportConfig()
) {
var age: Int = 10
set(value) {
println("setter $value")
field = value
}
val createTimeShow: () -> String
get() = { this.toString() }
}
Copy the code
5.3 Kotlin NULL Judgment
All variables declared above are non-empty variables, that is, null values are not allowed. If you need to declare a variable to be nullable, simply add? To the variable type.
valn: String? =null
Copy the code
To declare a variable to be null, simply add? To the variable type.
// If n is null, the compiler will report an error
n.length
// The correct way to use it is to short before using it
// If the variable is empty, just add? To the variable type. , so that the length property is not accessedn? .length// if a nullable variable is not null
// Can add!! Tell the compiler it's not nulln!! .lengthCopy the code
5.4 Kotlin String Template
val i=10
val s="i=$i"// I =10
val s="adb"
val str="$s.length is ${s.length}"Adb. Length is 3
Copy the code
5.5 Kotlin double colon operator
The double colon operator means passing a method (variable) as an argument to another method (variable) for use, similar to Java8
/** * converts the function name to the corresponding stored data object ** /
fun nameToInfoClass(name: String): Class<*> {
return when (name) {
RabbitMonitorProtocol.BLOCK.name -> RabbitBlockFrameInfo::class.java
RabbitMonitorProtocol.APP_SPEED.name -> RabbitAppStartSpeedInfo::class.java
RabbitMonitorProtocol.FPS.name -> RabbitFPSInfo::class.java
RabbitMonitorProtocol.MEMORY.name -> RabbitMemoryInfo::class.java
RabbitMonitorProtocol.EXCEPTION.name -> RabbitExceptionInfo::class.java
RabbitMonitorProtocol.NET.name -> RabbitHttpLogInfo::class.java
RabbitMonitorProtocol.SLOW_METHOD.name -> RabbitSlowMethodInfo::class.java
RabbitMonitorProtocol.BLOCK_CALL.name -> RabbitBlockFrameInfo::class.java
RabbitMonitorProtocol.GLOBAL_MONITOR.name -> RabbitAppPerformanceInfo::class.java
RabbitMonitorProtocol.ANR.name -> RabbitAnrInfo::class.java
else -> RabbitFPSInfo::class.java
}
}
Copy the code
5.6 Kotlin anonymous Functions
Kotlin normal function
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- a case -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
a(fun b(param: Int): String {
return param.toString()
});
val d = fun b(param: Int): String {
return param.toString()
}
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the second case -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -
view.setOnClickListener(new OnClickListener() {
@Overridevoid onClick(View v) { switchToNextPage(); }});Copy the code
Kotlin anonymous function
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- a case -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
a(fun(param: Int): String {
return param.toString()
});
val d = fun(param: Int): String {
return param.toString()
}
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- second case -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
fun setOnClickListener(onClick: (View) - >Unit) {
this.onClick = onClick
}
view.setOnClickListener(fun(v: View): Unit) {
switchToNextPage()
})
Copy the code
5.7 Kotlin lambda syntax sugar
view.setOnClickListener() { v: View ->
switchToNextPage()
}
//-----------------------------------------------
view.setOnClickListener { v: View ->
switchToNextPage()
}
//-----------------------------------------------
mSimpleListRv.setOnClickListener {
startActivity(Intent(this, SimpleListActivity::class.java))
}
//-----------------------------------------------
view.setOnClickListener {
switchToNextPage()
it.setVisibility(GONE)
}
Copy the code
5.8 Kotlin expressions
5.8.1 Kotlin for loops and range expressions
5.8.1.1 Kotlin for Loop
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- positive sequence traversal -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
for (index in 1.100.){
print(index)
}
Copy the code
5.8.1.2 Range expressions
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- reverse traversal -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
for (index in 100 downTo 1){
print(index)
}
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- don't use 1 as the traversal of the step length -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
for (index in 1.100. step 2){
print(index)// Output 1.. 3.. 5...
}
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- to create a does not contain the element at the end of range -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
for (index in 1 until 10){
println(index)/ / output 1.. 9
}
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- through an array/list, want to take out at the same time the subscript and element -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
val array = arrayOf("a"."b"."c")
for ((index,e) in array.withIndex()){
println(The subscript ="$index- element =$e")}/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- through an array/list, only remove the subscript -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
val array = arrayOf("a"."b"."c")
for (index in array.indices){
println("index=$index")// output 0,1,2
}
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- traverse take element -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
val array = arrayOf("a"."b"."c")
for (element in array){
println("element=$element")/ / output a, b, c
}
Copy the code
5.8.2 Kotlin enumeration and WHEN expressions
5.8.2.1 kotlin enumeration
In Kotlin, enumeration types exist as classes and are therefore called enumerations. The code is as follows:
enum class Color {
RED, GREEN, BLUE
}
/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- use -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
var color: Color = Color.BLUE
var color2 = Color.GREEN
// Compare two enumerated type variables
var bool: Boolean = color == color2
//--------------- specifies the value ------------------- for the enumeration value
enum class Direction private constructor(var value: Int) {
NORTH(1), WEST(2), EAST(3), SOUTH(4)}Copy the code
5.8.2.2 Kotlin WHEN expression
The when expression supports auto-casting as follows:
when (view) {
is TextView -> toast(view.text)
is RecyclerView -> toast("Item count = ${view.adapter.itemCount}")
is SearchView -> toast("Current query: ${view.query}")
else -> toast("View type not supported")}Copy the code
5.8.3 Kotlin infix expression
A kotlin infix expression is a function that takes only one argument and is decorated with infix. This is what we call a custom infix expression.
/ / book
class Book{
// Pass in any type, return a Boolean parameter
infix fun on(any: Any): Boolean{
return true}}/ / table
class Desk
fun main(args: Array<String>) {
if(Book() on Desk()){
println("The book is on the table")}}Copy the code
5.8.3 Kotlin compound expression
5.8.3.1 ‘? . ‘
? If foo is empty, null is returned, otherwise foo.bar() is returned.
if(foo ! =null) {return foo.bar()
}else{
return null
}
Copy the code
5.8.3.2 ‘? : ‘
? : Returns data when the data is not empty, and returns the merged data when the data is empty. Using this operator, you can easily convert a nullable type to a non-nullable type. The code is as follows:
if(foo! =null)
{
foo
}
else{ bar } foo? .length? : -1
Copy the code
5.8.3.3 ‘!!!!! ‘
In the Kotlin!!!!! Represents a non-empty assertion operator, detailed as follows:
if(foo! =null)
{
foo
}else
{
return NullPointerException
}
Copy the code
5.8.3.4 ‘as? ‘
Kotlin can use the secure conversion operator as? , it can return null on failure.
foo as? type
if(foo is Stype)
{
foo as Type
}else
{
null
}
Copy the code
5.8.3.5 ‘? ‘
? Representing nullable and non-nullable types,Kotlin’s type system aims to eliminate the danger of null references from code, as detailed below:
foo?
varfoo? ="abc"
foo=null
// Foo can be null on success
var foo="abc"
foo=null
// foo cannot be empty when a compilation fails
Copy the code
Kotlin is object oriented
6.1 Kotlin inheritance and construction
Kotlin inherits all ‘:’ without distinction between extend or implement, but there are a few rules to note:
6.2 kotlin class
6.2.2 kotlin object class
The object global declaration only has one object, so it is a natural singleton model
6.2.2 kotlin data classes
To declare a data class in Kotlin, the following criteria must be met:
- The data class must have a constructor that contains at least one argument
- The data class constructor parameter enforces the declaration of val or var
- Data class is not preceded by abstract, open or inner
6.2.3 Kotlin inner class
6.3 kotlin interface
6.4 Objects associated with Kotlin
6.5 Kotlin modifier
6.5.1 Restrict modifiers
- Val translates to bytecode as final
- private
- internal
- by
The by keyword in Kotlin is used to simplify the implementation of the proxy (delegate) pattern, allowing not only class proxies but also class properties to listen for property changes
6.5.2 Visible modifiers
Use of nested classes: If you want to nest a class in Kotlin, you need to append the inner class to the inner class
// Nested classes are static classes that have nothing to do with external classes
fun main(args : Array<String>){
var ot = OutClass().innerClass()
ot.hello()
}
class OutClass{
var name ="Li Wu"
//inner denotes inner class
inner class innerClass{
var name = "Zhang"
fun hello(a){
println("Hello$name")
// The inner class uses this to access variables of the outer class
println("Hello${[email protected]}")}}}Copy the code
7. To summarize
Kotlin and Java8 are both different from each other. Kotlin and Java8 are different from each other. Kotlin and Java8 are different from each other. Use of Kotlin methods and variables, Kotlin string templates, Lambada expressions, and practical use of various expressions. Well, that’s all for Kotlin. If you have any questions, please leave them in the comments
Everybody see officer, see all see, help point a praise bai ~