kotlin简单规则(类和继承,接口,可见修饰符,密封类,嵌套类,枚举类,别名,内联类,委派属性,函数,中缀表示法,迭代器,类型检查和转换,可调用的引用)

本文介绍了学习 Kotlin 可查看官方文档。详细阐述了 Kotlin 的多种特性,如类和继承、接口、可见性修饰符等。还说明了密封类的特点,函数无返回值时返回类型为 Unit,以及中缀函数的调用要求和条件等信息技术相关内容。

版权声明:本文为延成原创文章,转载请标明出处

学习kotlin可直接查看Kotlin官方文档,既方便又实用

类和继承


	class Person constructor(firstName: String) { ... }
	
	//如果主构造函数没有任何注释或可见性修饰符, 则可以省略constructor关键字:
	class Person(firstName: String) { ... }
	
	class InitOrderDemo(name: String) {
	    val firstProperty = "First property: $name".also(::println)
	    
	    init {
	        println("First initializer block that prints ${name}")
	    }
	    
	    val secondProperty = "Second property: ${name.length}".also(::println)
	    
	    init {
	        println("Second initializer block that prints ${name.length}")
	    }
	}
	
	First property: hello
	First initializer block that prints hello
	Second property: 5
	Second initializer block that prints 5

接口


	 interface A {
	    fun foo() { print("A") }
	    fun bar()
	}
	
	interface B {
	    fun foo() { print("B") }
	    fun bar() { print("bar") }
	}
	
	class C : A {
	    override fun bar() { print("bar") }
	}
	
	class D : A, B {
	    override fun foo() {
	        super<A>.foo()
	        super<B>.foo()
	    }
	
	    override fun bar() {
	        super<B>.bar()
	    }
	}

可见性修饰符


	package foo
	
	private fun foo() { ... } // 在example.kt中可见
	
	public var bar: Int = 5 //属性随处可见
	
	    private set         // setter 仅在 example.kt中可见
	    
	internal val baz = 6    // 在同一模块内可见

密封类

  • 密封类本身是抽象的,它不能直接实例化,并且可以具有抽象成员。
  • 密封类不允许具有非私有构造函数(默认情况下它们的构造函数是私有的)。
  • 请注意,扩展密封类(间接继承者)的子类的类可以放在任何位置,而不必放在同一个文件中。
	sealed class Expr
	data class Const(val number: Double) : Expr()
	data class Sum(val e1: Expr, val e2: Expr) : Expr()
	object NotANumber : Expr()
	
	fun eval(expr: Expr): Double = when(expr) {
	    is Const -> expr.number
	    is Sum -> eval(expr.e1) + eval(expr.e2)
	    NotANumber -> Double.NaN
	    // the `else` clause is not required because we've covered all the cases
	}

嵌套类

	class Outer {
	    private val bar: Int = 1
	    inner class Inner {
	        fun foo() = bar
	    }
	}
	
	val demo = Outer().Inner().foo() // == 1

枚举类

	enum class Color(val rgb: Int) {
	        RED(0xFF0000),
	        GREEN(0x00FF00),
	        BLUE(0x0000FF)
	}
	
	enum class ProtocolState {
	    WAITING {
	        override fun signal() = TALKING
	    },
	
	    TALKING {
	        override fun signal() = WAITING
	    };
	
	    abstract fun signal(): ProtocolState
	}

别名

	 class A {
	    inner class Inner
	}
	class B {
	    inner class Inner
	}
	
	typealias AInner = A.Inner
	typealias BInner = B.Inner

内联类

	inline class Password(val value: String)
	// 没有实际发生类'Password'的实例化
	// 在运行时'securePassword'只包含'String'
	val securePassword = Password("Don't try this in production")

委派属性

	interface Base {
	    val message: String
	    fun print()
	}
	
	class BaseImpl(val x: Int) : Base {
	    override val message = "BaseImpl: x = $x"
	    override fun print() { println(message) }
	}
	
	class Derived(b: Base) : Base by b {
	    // This property is not accessed from b's implementation of `print`
	    override val message = "Message of Derived"
	}
	
	fun main() {
	    val b = BaseImpl(10)
	    val derived = Derived(b)
	    derived.print()
	    println(derived.message)
	}

函数

  • 如果函数没有返回任何有用的值,则其返回类型为Unit。Unit是只有一个值的类型 - Unit。不必显式返回此值:

fun printHello(name: String?): Unit {
    if (name != null)
        println("Hello ${name}")
    else
        println("Hi there!")
    // `return Unit` or `return` is optional
}

//在Unit返回类型声明也是可选的。上面的代码相当于:
fun printHello(name: String?) { ... }
	

中缀表示法

  • 用infix关键字标记的函数也可以使用中缀表示法调用(省略点和调用的括号)。中缀函数必须满足以下要求:
  • 它们必须是成员函数或扩展函数 ;
  • 他们必须有一个参数;
  • 参数不能接受可变数量的参数,并且必须没有默认值。
infix fun Int.shl(x: Int): Int { ... }

// calling the function using the infix notation
1 shl 2

// is the same as
1.shl(2)

迭代器

val numbers = listOf("one", "two", "three", "four")
val numbersIterator = numbers.iterator()
while (numbersIterator.hasNext()) {
    println(numbersIterator.next())
}


val numbers = listOf("one", "two", "three", "four")
for (item in numbers) {
    println(item)
}


val numbers = listOf("one", "two", "three", "four")
numbers.forEach {
    println(it)
}

类型检查和转换

if (obj is String) {
    print(obj.length)
}

if (obj !is String) { // same as !(obj is String)
    print("Not a String")
}
else {
    print(obj.length)
}

可调用的引用

fun isOdd(x: Int) = x % 2 != 0

val numbers = listOf(1, 2, 3)
println(numbers.filter(::isOdd))

[1, 3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值