In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you the relevant knowledge of how to use Kotlin. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
1. How to define variables
Java defines the way variables are written:
String string = "Hello"
The basic equivalent of Kotlin defines how to write variables:
Var string: String = "Hello"
Java defines how to write final variables:
Final String string = "Hello"
Notice that the previous one is a compile-time constant, which should be written as follows in Kotlin:
Const val string: String = "Hello"
It's also a final variable, and Java says:
Final String string = getString ()
Notice that this is not a compile-time constant, as Kotlin wrote:
Val string: String = getString ()
In addition, Kotlin has the feature of type derivation, so the above variable definitions can basically omit the type String.
two。 How to define a function
How to define a function, that is, a method, in Java needs to be defined in a class:
Public boolean testString (String name) {...}
Equivalent Kotlin writing:
Fun testString (name: String): Boolean {...}
Notice that the position of the return value is placed after the parameter.
3. How to define static variables and methods
Static methods or variables of Java only need to add a static:
Public class Singleton {private static Singleton instance =...; public static Singleton getInstance () {... Return instance;}}
The literal translation in Kotlin means:
Class KotlinSingleton {companion object {privateval kotlinSingleton = KotlinSingleton () @ JvmStatic fun getInstance () = kotlinSingleton}}
Pay attention to the writing of getInstance. The JvmStatic annotation compiles the getInstance method to the same signature as the static method of Java. Without this annotation, the method cannot be called in Java like calling the static method of Java.
In addition, for scenarios with static methods and variables, package-level functions are recommended in Kotlin.
4. How to define an array
Java's array is very simple and, of course, somewhat abstract, after all, it is a class generated at compile time:
String [] names = new String [] {"Kyo", "Ryu", "Iory"}; String [] emptyStrings = new String [10]
Kotlin's array is actually more realistic and looks easier to understand:
Val names: Array = arrayOf ("Kyo", "Ryu", "Iory") val emptyStrings: Array = arrayOfNulls (10)
Notice that Array T is the type of array element. Besides, String? Represents a String type that can be null.
The use of arrays is basically the same. It should be noted that in order to avoid the overhead of packing and unpacking, Kotlin provides customized array types for basic types, including Int, Short, Byte, Long, Float, Double, Char and other basic types, written as XArray. For example, the customized array of Int is IntArray. If we want to define an integer array, write as follows:
Val ints = intArrayOf (1,3,5)
5. How to write variable length parameters
The variable length parameters of Java are written as follows:
Void hello (String... Names) {.}
The variable length parameters of Kotlin are written as follows:
Fun hello (vararg names: String) {}
6. How to write ternary operators
Java can write ternary operators:
Int code = isSuccessfully? 200: 400
Many people complain why Kotlin doesn't have this operator. It is said that it is because the scenario used in Kotlin is much more complex than Java, so adding this ternary operator will cause more trouble to the syntax parser, and the same is true for Scala. So in this case, how do we write it in Kotlin?
Int code = if (isSuccessfully) 200 else 400
Notice that statements like if else are also expressions, unlike Java.
7. How to write main function
There is only one way to write Java:
Class Main {public static void main (String... Args) {.}}
Note that the parameter can be a variable length parameter or an array, both of which can be used.
The corresponding Kotlin,main function is written as follows:
Class KotlinMain {companion object {@ JvmStatic fun main (args: Array) {}
Kotlin can have package-level functions, so we don't need to declare a class to wrap the main function:
Fun main (args: Array) {...}
8. How to instantiate a class
Languages like Java and C++ often use the keyword new when constructing objects, such as:
Date date = new Date ()
The keyword new is not required when Kotlin constructs an object, so the above writing is equivalent to:
Val date = Date ()
9. How to write Getter and Setter methods
Java's Getter and Setter are commonly known as conventions, not grammatical features, so they are relatively free to define:
Public class GetterAndSetter {private int x = 0; public int getX () {return x;} public void setX (int x) {this.x = x;}}
Kotlin has attributes:
Class KotlinGetterAndSetter {var x: Int = 0 set (value) {field = value} get () = field}
Notice that we explicitly define getter and setter,field for x as the real variables behind x, so setter actually assigns a value to field, while getter returns field. If you want to control the access to x, you can do so by customizing getter and setter:
Class KotlinGetterAndSetter {var x: Int = 0 set (value) {val date = Calendar.getInstance () .apply {set (2017, 2) 18)} if (System.currentTimeMillis () < date.timeInMillis) {println ("Cannot be set before 2017.3.18")} else {field = value}} get () {println ("Get field x: $field") return field}}
10. How to delay initialization of member variables
If the class member variables defined by Java are not initialized, then the base types are initialized to their default values, such as int initialization to 0quotation Boolean initialization to false, and non-primitive members to null.
Public class Hello {private String name;}
Similar code is literally translated in Kotlin as:
Class Hello {private var name: String? = null}
Nullable types are used, and the side effect is that every time you want to use name, you need to determine whether it is null. If you do not use controllable types, you need to add the lateinit keyword:
Class Hello {private lateinit var name: String}
Lateinit is used to tell the compiler that the variable name will be disposed of later.
For final member variables, Java requires that they must be initialized in the constructor or building block:
Public class Hello {private final String name = "Peter";}
That is, if I want to define a final variable that can be delayed until it is actually used and initialized, this is not possible in Java.
Kotlin has a solution. You can use lazy as a delegate:
Class Hello {privateval name by lazy {NameProvider.getName ()}}
Only when the attribute name is used, the Lambda after lazy is executed and the value of name is actually calculated.
11. How to get an example of class
In Java:
Public class Hello {...}... Class clazz = Hello.class; Hello hello = new Hello (); Class clazz2 = hello.getClass ()
Earlier we showed two ways to get class, one using the class name directly and the other through the class instance. When you first came into contact with Kotlin, the method of getting Java Class is easy to confuse.
Class Hello val clazz = Hello::class.java val hello = Hello () val clazz2 = hello.javaClass
The Kotlin code with the same effect does look strange, but in fact Hello::class gets the KClass of Kotlin, which is the type of Kotlin, and if you want to get a Class instance of Java, you need the previous approach.
These are all the contents of the article "how to use Kotlin". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.