当前位置:网站首页>Kotlin basic objects, classes and interfaces
Kotlin basic objects, classes and interfaces
2022-06-13 06:25:00 【m0_ forty-seven million nine hundred and fourteen thousand one 】
One . object
1.object keyword
Use object keyword , You can define a class that produces only one real column - Single case
1. Object declaration
Object declarations help organize code and manage state , In particular, manage some consistency states throughout the application operation life cycle .
//object Represents a singleton
object ApplicationSingle {
init {
print("ApplicationSingle")
}
fun setMatter(){
print("setMatter")
}
}
fun main() {
print(ApplicationSingle)
ApplicationSingle.setMatter()
}
2. Object expression
Sometimes you want to use an instance of a class , Only once , So for this kind of class instance that is lost after use , Even naming can be saved . In the following example, the object expression XX Subclasses of classes , Use object The key word , Once instantiated , Only one instance of this anonymous class can exist .
// Parent class
open class Player{
open fun load()="loading nothing.."
}
fun main(){
// Object expression
// Anonymous inner class Single case Inherit subclasses
val p=object : Player(){
override fun load()="anonymous class"
}
print(p.load())
}3. Companion
If you want to bundle the initialization of an object with a class instance , Consider using companion objects , Use companion Modifier , Only one companion object can be defined in a class definition
class ConfigMap {
// The companion object is a And will only be created when called It's also static
companion object{
private const val PATH="xxxx"
fun load()= File(PATH).readBytes()
}
}
fun main() {
ConfigMap.load()
}Two . class
1. Nested class
If one class is only useful to another , Then it is logical to embed it in the class and use the two classes to keep it together , You can use nested classes .
class ImplantClass {
// Nested class
class Equipment(var name:String){
fun show()= print("equipment:$name") // STOPSHIP: 2021-09-11
}
fun battle(){}
}
fun main(){
// call chaining
ImplantClass.Equipment("xiaohua").show()
}2. Data class
1. Definition
Data class , Is the class used to store data . Data classes directly provide toString Method implementation .
Data classes cannot be used abstract,opne,sealed and inner Modifier
== Symbols by default , Comparing two common class objects is comparing their reference values , By default, data classes provide equals and hashCode Implementation of function .、
data class Coordinate (var x:Int,var y:Int){
private val isInBounds=x>0 && y>0
// rewrite
override fun toString(): String {
return "Coordinate(x=$x, y=$y, isInBounds=$isInBounds)"
}
}
fun main() {
print(Coordinate(10,20))
//data Class compares values
//class Class compares memory addresses
print(Coordinate(10,20)==Coordinate(10,20))
val coordinate = Coordinate(10, 20)
}2.copy
In addition to rewriting Any Some functions of class , Provide a better default implementation , The data class also provides a function , It can be used to easily copy an object . Suppose you want to create a Student Solid column , except name attribute , It has and another existing Student Instance exactly the same property value , If Student It's a data class , Then copy the existing Student Real columns are simple , Just call copy function , Just pass in the value for the attribute you want to modify .
data class Coordinate (var x:Int,var y:Int){
private val isInBounds=x>0 && y>0
init {
println("initializing student")
}
constructor(_x:Int):this(_x,20){
}
// rewrite
override fun toString(): String {
return "Coordinate(x=$x, y=$y, isInBounds=$isInBounds)"
}
}
fun main() {
val coordinate = Coordinate(10, 20)
//copy Only the properties of the primary constructor can be copied
val copy = coordinate.copy(20)
print(coordinate)
print(copy)
}
3. deconstruction
The background implementation of the deconstruction declaration is the declaration component1,component2 Equal component function , Let each function be responsible for managing an attribute data you want to return , If you define a Data class , It will automatically add the corresponding component function without all the properties defined in the main constructor
class PlayerScore (private val experience:Int, private val level:Int) {
// Structural decomposition of common classes To add a progressive function
operator fun component1()=experience
operator fun component2()=level
}
fun main() {
val (x,y)=PlayerScore(10,20)
print("$x $y ")
//data Classes can be constructed directly
val (a,s)=Coordinate(10,20)
print("$a $s")
}4. Operator overloading
If you want to apply a built-in operator to a custom class ( Ordinary classes are also OK ) On the body , You must rewrite the operator function , Tell the compiler how to operate custom classes .
data class Coordinate2 (var x:Int,var y:Int){
val isInBounds=x>0 && y>0
// Operator overloading
operator fun plus(other:Coordinate2)=Coordinate2(x+other.x,y+other.y)
}
fun main() {
val coordinate2 = Coordinate2(10, 20)
val coordinate1 = Coordinate2(10, 20)
// This triggers rewriting plus Method Put two classes of x And y Add up
println(coordinate2+coordinate1 )
}
Common operators :
The operator | Function name | effect |
+ | plus | Add one object to another |
+= | plusAssign | Add one object to another , Then assign the result to the first object |
== | equals | If two objects are equal , Then return to true, Otherwise return to false |
> | compareTo | If the object on the left is larger than the object on the right , Then return to true, Otherwise return to false |
[ ] | get | Returns the element at the specified location in the collection |
.. | rangeTo | Create a range object |
in | contains | If the object is included in the collection , Then return to true |
3. Enumeration class
1. Definition
Enumeration class , A special class used to define a collection of constants .
enum class Direction {
EAST,
WEST,
SOUTH,
NORTH;
}
fun main() {
// These are all examples of this
print(Direction.EAST)
print(Direction.EAST is Direction)
}Of course, enumeration classes can also define functions .
enum class Direction(private val coordinate: Coordinate) {
EAST(Coordinate(1,0)),
WEST(Coordinate(-1,0)),
SOUTH(Coordinate(-1,0)),
NORTH(Coordinate(1,0));
// If there is a value transfer requirement, you can use the encapsulation class
var licenseId :String?=null
fun updateCoordinate(playerCoordinate: Coordinate)
=Coordinate(playerCoordinate.x+coordinate.x,playerCoordinate.y+coordinate.y)
}
fun main() {
// When you call a function , Enumeration constants are used , So it should be called like this
print(Direction.EAST.updateCoordinate(Coordinate(10,20)))
}
2. Algebraic data type
A closed set that can be used to represent a set of subtypes , Enumerating classes is a kind of simple ADT.
enum class Direction(private val coordinate: Coordinate) {
EAST(Coordinate(1,0)),
WEST(Coordinate(-1,0)),
SOUTH(Coordinate(-1,0)),
NORTH(Coordinate(1,0));
// If there is a value transfer requirement, you can use the encapsulation class
var licenseId :String?=null
fun updateCoordinate(playerCoordinate: Coordinate)
=Coordinate(playerCoordinate.x+coordinate.x,playerCoordinate.y+coordinate.y)
}
class Driver(var status : Direction){
fun checkLicense():String{
return when(status){
Direction.EAST->" Not qualified "
Direction.WEST->" Admission "
Direction.SOUTH->" Study "
Direction.NORTH->" Qualified ${status.licenseId}"
}
}
}
fun main() {
print(Driver(Direction.EAST).checkLicense())
}4. Sealing class
For the more complicated ADT, You can use Kotlin The sealing class of (sealed class) To implement more complex definitions , A sealed class can be used to define a class similar to an enumeration class ADT, But you can control a subtype more flexibly .
A sealed class can have subclasses , To inherit the sealed class , these Subclasses must be defined in the same file as it .
// seal up
sealed class LicenseStatus2 {
// There is no need for him to use it There is no attribute , If you use class Waste memory
object UnQualified : LicenseStatus2()
object Learning : LicenseStatus2()
class Qualified(val name:String) : LicenseStatus2()
}
class Driver2(var status :LicenseStatus2){
fun checkLicense():String{
return when(status){
is LicenseStatus2.UnQualified->" Not qualified "
is LicenseStatus2.Learning->" learning "
is LicenseStatus2.Qualified->" Qualified , Driver's license number :${(this.status as LicenseStatus2.Qualified).name}"
}
}
}
fun main() {
print(Driver2(LicenseStatus2.Qualified("20000817")).checkLicense())
}Two . Interface
1. Interface definition
Kotlin Specify that all interface properties and function implementations should use override keyword , The functions defined in the interface do not need open Keyword modification , Their default is open Of .
interface Movable {
fun move()
}
class Car :Movable{
override fun move() {
}
}2. Default implementation
Provide default properties in the interface getter Method and function implementation .
interface Movable {
val maxSpeed: Int
get() = (1..500).shuffled().last()
var wheels:Int
//get() = (1..500).shuffled().last()
fun move(movable: Movable):String
}
class Car(override var wheels: Int=4) :Movable{
override val maxSpeed: Int
get() = super.maxSpeed
override fun move(movable: Movable): String {
return " "
}
}3、 ... and . abstract class
1. Abstract class definition
To define an abstract class , You need to add... Before the definition abstract keyword , In addition to the specific function implementation , Abstract classes can also include abstract functions —— It's just a definition , No function implementation .
abstract class Gun(val range: Int) {
abstract fun trigger(): String
}
class M16(_price: Int) : Gun(range = 80) {
override fun trigger(): String {
return "M16 shooting"
}
}
fun main() {
val g: Gun = M16(120)
println(g.trigger())
}边栏推荐
- Applet Use of spaces
- 二分查找
- AI realizes "Resurrection" of relatives | old photo repair | old photo coloring, recommended by free app
- js将文本转成语言播放
- Uni app provincial and urban linkage
- 无刷直流电机矢量控制(四):基于滑模观测器的无传感器控制
- Solution: vscode open file will always overwrite the last opened label
- View绘制整体流程简析
- Echart histogram: stack histogram value formatted display
- [JS] handwriting call(), apply(), bind()
猜你喜欢

微信小程序:点击事件获取当前设备信息(基础)

Wechat applet custom tabbar (session customer service) vant

The web server failed to start Port 7001 was already in use

Basic knowledge of knowledge map

js将文本转成语言播放

Solutions to common problems in small program development

MFS详解(六)——MFS Chunk Server服务器安装与配置

Echart histogram: echart implements stacked histogram

MFS详解(五)——MFS元数据日志服务器安装与配置
![[DP 01 backpack]](/img/be/1e5295684ead652eebfb72ab0be47a.jpg)
[DP 01 backpack]
随机推荐
SSM integration
[JS] handwriting call(), apply(), bind()
Uniapp (upload local pictures, preview pictures, convert Base64 format, upload audio files)
USB 0xc0000011 error
免费录屏软件Captura下载安装
自定义View
ADB shell sendent debug input event
Win10 drqa installation
Wechat applet (pull-down refresh data) novice to
自定义View —— 可伸展的CollapsExpendView
JVM基础
【js】var、let、const
微信小程序:基础复习
Super model logo online design and production tool
Applet Use of spaces
Detailed explanation of PHP distributed transaction principle
How to view APK version number from apk
《MATLAB 神经网络43个案例分析》:第11章 连续Hopfield神经网络的优化——旅行商问题优化计算
【var const let区别】
App performance test: (III) traffic monitoring