Kotlin初体验

该篇博文只是作为本人的学习记录,对别人没有参考价值,请不要围观

类和对象

package cainiao.clazz

import com.sun.corba.se.impl.orb.ParserTable
import kotlin.concurrent.fixedRateTimer

private fun main(args: Array<String>) {
    /**
     * abstract, final, enum, open, annotation
     * ******************************************
     * private, seen in same file
     * protected, seen in same file or subclass
     * public, seen at all places
     * internal, seen in same module
     */

//    var test = Test()
//    test.setInterface(object : TestInterface {
//        override fun test() {
//            println("anonymous class")
//        }
//    })

//    val  demo = Outer1().Inner().foo()
//    println(demo)
//    val  demo2 = Outer1().Inner().innerTest()
//    println(demo2)

//    val demo = Outer.Nested().foo()
//    println(demo)

//    var p = Person("ren")
//    p.lastName = "kai"
//
//    println("lastName: ${p.lastName}")
//    p.no = 8
//    println("no: ${p.no}")
//    p.no = 20
//    println("no: ${p.no}")
//    print("firstName: ${p.firstName}")
//
//    var p2 = Person("Kyle", 12)
}

class Test {
    var v = "member field"
    fun setInterface(test: TestInterface) {
        test.test()
    }
}

interface TestInterface {
    fun test()
}

class Outer1 {
    private val bar = 1
    var v = "member field"

    inner class Inner {
        fun foo() = bar  //visit out member field
        fun innerTest() {
            var o = this@Outer1 // fetch out class object
            print("inner class can access out class member, like: "+o.v)
        }
    }
}

//out class
class Outer {
    private val bar : Int = 1
    class Nested {
        fun foo() = 2
    }
}

//open means it's non-final, so can be inhered
open class Base{
    open fun f() {}
}

//abstract class
abstract class Derived : Base() {
    override fun f() {
        super.f()
    }
}


//normal class
class Person constructor(firstName: String) {
    init {
        println("firstname is $firstName")
    }

    constructor(name: String, rank: Int) : this(name) {
        println("name ranks $rank")
    }

    val firstName = firstName
    get() = field.toUpperCase()
    var lastName : String = "zhang"
    get() = field.toUpperCase() //backing field
    set

    var no : Int = 100
    get() = field
    set(value) {
        field = if (value<10) value else -1
    }

    var height : Float = 145.1f
    private set
}

类的继承1

package cainiao.clazz

import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent

fun main(args: Array<String>) {
    val b = BaseImpl(10)
    MDerived(b).print()

//    var s1 = Site
//    var s2 = Site
//    s1.url = "cnki.net"
//    println(s1.url)
//    println(s2.url)

    /**
    //using class
    val a1:AAA<*> = AAA(12, "String", Apple("apple"))
    val a2:AAA<Any?> = AAA(12, "String", Apple("appple"))
    val apple = a1.t3  //it's any
    println(apple)
    val apple2 = apple as Apple
    println(apple2.name)
    //using Array
    val li:ArrayList<*> = arrayListOf("String", 1, 1.3f, Apple("apple"))
    for (it in li) println(it)
    **/


//    var strDCo = Runnb2("aaa")
//    var antDCo = Runnb2("1111")
//    antDCo = strDCo
//    println(antDCo)

//    var strCo:Runoob<String> = Runoob("aaaaa")
//    var anyCo:Runoob<Any> = Runoob("bbbbbb")
//    anyCo = strCo;
//    println(anyCo.foo())

//    sort(listOf(11,22,33))
//    sort(listOf(HashMap<Int, String>))

//    doPrintln(111)
//    doPrintln("222")
//    doPrintln('3')

//    val box4 = boxInt(11)
//    println(box4.value)

//    var boxInt = Box(10)
//    var boxString = Box("Kyle")
//    println(boxInt.value)
//    println(boxString.value)

//    val d : Double = 12.0
//    println(eval(Const(d)))

//    val jack = UserData(name = "Jack", age = 15)
//    val olderJack = jack.copy(age = 20)
//    println(jack)
//    println(olderJack)
//
//    val (name, age) = jack
//    println("$name, $age years of age")

//    val f : F = F()
//    val g : G = G()
//    g.caller(f)

//    println("no: ${MyClass.no}")
//    MyClass.foo()

//    var list : List<String> = ArrayList()
//    println(list.lastIndex)

//    var t = null
//    println(t.toString())

//    printFoo(Dd())

//    val v = mutableListOf(1,2,3)
//    v.swap(0, 2)
//    println(v.toString())

    //User("Kyle").Print()
}

//create interface
interface MBase {
    fun print()
}

//class what is been delegated
class BaseImpl(val x:Int) : MBase {
    override fun print() {
        print(x)
    }
}

//build delegated class via 'by'
class MDerived(b:MBase) : MBase by b

object DefaultListener : MouseAdapter() {
    override fun mouseClicked(p0: MouseEvent?) {
        super.mouseClicked(p0)
    }

    override fun mouseEntered(p0: MouseEvent?) {
        super.mouseEntered(p0)
    }
}

//object expression and object declare
object Site {
    var url:String = ""
    var name:String="Cainiao"
}

enum class RGB{ R, G, B}
inline fun <reified T:Enum<T>> printAllValues() {

}

enum class Color(val rgb:Int) {
    RED(0xaa), GREEN(0xbb), BLUE(0xcc)
}

enum class ProtocolState {
    WAITING {
        override fun signal() : ProtocolState {
            return TALKING
        }
    },

    TALKING {
        override fun signal(): ProtocolState {
            return WAITING
        }
    };

    //declare anonymous class and function
    abstract fun signal() : ProtocolState
}

class AAA<T>(val t1:T, val t2:T, val t3:T)
class Apple(var name:String) {
    override fun toString(): String {
        return "Apple(name='$name')"
    }
}

class Runnb2<in A>(a: A) {
    fun foo(a: A) {

    }
}

//covariable -- test out
//in -> consumer, out -> productor
class Runoob<out A>(val a:A) {
    fun foo():A {
        return a
    }
}

//generic constraint
fun <T: Comparable<T>> sort(list: List<T>) {

}

fun <T> doPrintln(content:T) {
    when(content) {
        is Int -> println("int val: $content")
        is String -> println("string val: $content")
        else -> println("not int, nor string")
    }
}

//generic function
fun  <T> boxInt(value: T) = Box(value)

//generic class
class Box<T>(t:T) { var value = t }
val box : Box<Int> = Box(1)


// sealed class refer to limited class
sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val  e1:Expr, val e2:Expr) : Expr()
object NotNumber : Expr()
fun eval(expr: Expr):Double = when(expr) {

    is Const -> expr.number
    is Sum -> eval(expr.e1) + eval(expr.e2)
    NotNumber -> Double.NaN
}

//data class
data class UserData(val name: String, val age: Int)


class F {
    fun ff() { println("ff() in F")}
}

class G {
    fun gg() { println("gg() in G")}
    fun F.ff_() {
        ff()  //call F.ff
        gg()  //call G.gg
    }
    fun caller(f:F) {
        f.ff_() // call extension
    }
}

//companion extension
class MyClass {
    companion object {
        // companion object
    }
}

fun MyClass.Companion.foo() {
    println("extension fun of companion object")
}

val MyClass.Companion.no : Int get() = 10


//insert field into a class
val <T> List<T>.lastIndex : Int
get() = size - 1

fun Any?.toString(): String {
    if (this == null) return "null"
    return toString()
}

//extension function is parsed in static, it's not determined dynamically
open class Cc
class Dd : Cc()
fun Cc.foo() = "cc"  //extension fun() foo
fun Dd.foo() = "dd"  //extension fun() foo
fun printFoo(cc: Cc) {
    println(cc.foo())
}


//insert a function in a class
fun MutableList<Int>.swap(index1 : Int, index2: Int) {
    val tmp = this[index1]
    this[index1] = this[index2]
    this[index2] = tmp
}

class User(var name : String)

//extend function
fun User.Print() {
    println("user name: ${name}")
}

 

类的继承2

package cainiao.clazz

fun main(args: Array<String>) {
    val c = Child()
    c.foo()
    c.bar()
    println(c)

//    var foo = Foo()
//    var bar = Bar()
//    println(foo.x)
//    println(bar.x)

//    C().f()

//    val stu = Student("Kyle", 18, "101", 800)
//    println(stu)
}

interface MyInterface {
    var name : String // name, abstract
    fun bar ()
    fun foo() {
        println("foo() in interface")
    }
}

class Child : MyInterface {
    override var name: String = "runoob"
    override fun bar() {
        println("bar() in sub class")
    }

    override fun toString(): String {
        return "Child(name='$name')"
    }

}

open class Foo {
    open var x = 1
}

class Bar : Foo() {
    override var x: Int
        get() = super.x
        set(value) {x = value}
}

open class A {
    open fun f() { println("A")}
    fun a() { println("a")}
}

interface B {
    fun f() { println("B")}
    fun b() { println("b")}
}

class C : A(), B {
    override fun f() {
        super<B>.f()
        super<B>.b()
    }
}

//base class
open class Person2(var name: String, var age: Int) {}

class Student(name: String, age: Int, var no: String, var score : Int) : Person2(name, age) {
    override fun toString(): String {
        name += "222"
        return "Student(no='$no', score=$score)"
    }
}

 

委托

package cainiao.clazz

import kotlin.properties.Delegates
import kotlin.reflect.KProperty

fun main(args: Array<String>) {

    val user = User3(mutableMapOf("name" to "Kyle", "age" to 39))
    println(user)
    user.age = 40
    println(user.map["age"])

//    var name : String by Delegates.notNull<String>()
//    println(name)

//    var ph = PostHierarchy()
//    ph.grade = "T1"
//    ph.grade = "T2"
//    ph.grade = "T3"
//
//    println(ph.grade)
//
//    ph.notChangeGrade = "T1"
//    ph.notChangeGrade = "T2"
//    ph.notChangeGrade = "T3"
//
//    println(ph.notChangeGrade)

//    var level:String by Delegates.observable("P0", {property: KProperty<*>, oldValue: String, newValue: String -> println("$oldValue -> $newValue") })
//    println(level)
    
//    val timeStamp by lazy { System.currentTimeMillis() }
//    println(timeStamp)
//    Thread.sleep(2000)
//    println(timeStamp)

//    val delegate = DelegateProperty()
//    println(delegate.content)
//
//    delegate.content = "kyle"

//    val haitao = Haitao(Daigou())
//    haitao.buyApple()
//    haitao.buyMac()
}

class User3(val map:MutableMap<String, Any?>) {
    var name : String by map
    var age: Int by map
    override fun toString(): String {
        return "User(name=$name, age=$age)"
    }

}

class PostHierarchy {
    var grade: String by Delegates.vetoable("T0", {
        property, oldValue, newValue -> true
    })

    var notChangeGrade : String by Delegates.vetoable("T0", {
        property, oldValue, newValue -> false
    })
}

/**************************property delegate**********************/
class DelegateProperty {
    var content : String by Content()
    override fun toString(): String {
        return "DelegateProperty(content='$content')"
    }
}

class Content {
    operator fun getValue(delegateProperty: DelegateProperty, property: KProperty<*>) : String {
        return "${delegateProperty} property '${property.name}' = 'Balalala ... ' "
    }

    operator fun setValue(delegateProperty: DelegateProperty, property: KProperty<*>, value: String) {
        println("${delegateProperty} property '${property.name}' is setting value: '$value'")
    }
}


/**************************class delegate*************************/

interface Buyer {
    fun buyApple()
    fun buyMac()
}

class Daigou : Buyer {
    override fun buyApple() {
        println("Ok, I'm buying Apple for Haitao")
    }

    override fun buyMac() {
        println("Ok, I'm buying Mac for Haitao")
    }

}

class Haitao(var realBuyer: Buyer) : Buyer by realBuyer {
    override fun buyApple() {
        println("Hello, Daigou! Please help me buy Apple")
        realBuyer.buyApple()
    }

    override fun buyMac() {
        println("Hello, Daigou! Please help me buy Mac")
        realBuyer.buyMac()
    }
}

参考:

http://www.runoob.com/kotlin/kotlin-tutorial.html

https://www.jianshu.com/p/40487ae860f2 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值