Kotlin学习笔记

kotlin学习笔记——接口与委托

2017-10-10  本文已影响5人  chzphoenix

Kotlin学习笔记系列:http://blog.csdn.net/column/details/16696.html

kotlin中的接口比java7中的要强大很多,与java8的很相似。
java7中的接口只能定义行为,不能实现。
kotlin中的接口也可以实现函数,但是与类的区别是它们是无状态(stateless)的,所以属性需要子类去重写。如:

interface FlyAnimal{  
     val wings : Wings  
     fun fly() = wings.move()  
}  
  
class Bird : FlyAnimal{  
     override val wings : Wings = Wings()  
}  

可以看到在接口中实现了函数,所以子类不必再重写,但是属性没有实现,子类需要去实现属性。



委托模式是kotlin原生支持的,所以我们不必去调用委托对象。委托者只需要实现实现接口的实例。如:

interface CanFly{  
     fun fly()  
}  
  
class AnimalWithWings : CanFly{  
     val wings : Wings = Wings()  
     override fun fly() = wings.move()  
}  
  
class Bird(f : CanFly) : CanFly by f  
  
//使用时  
val bird = Bird(AnimalWithWings())  
bird.fly()  

我们定义了一个接口CanFly,AnimalWithWings实现了这个接口,Bird也实现了这个接口但是委托了AnimalWithWings,所以Bird不用去实现接口了。
上面的实例中我们是将委托定义到构造函数中的,我们也可以直接指定委托来实例化对象。如:

class Bat : CanFly by AnimalWithWings()  
  
//使用时  
val bat = Bat()  
bat.fly()  
上一篇 下一篇

猜你喜欢

热点阅读