我知道你们大多数人已经知道动物牛草食物问题
-表示您具有类似下面的代码,并且对 Cow (继承了 Animal )具有类型约束,只能吃 SuitableFood (继承了食物)
以下是同一内容的SCALA表示形式
class Food
class Grass extends Food
class Cookies extends Food
class Fish extends Food
abstract class Animal {
type SuitableFood <: Food
def eat(food: SuitableFood)
}
class Cow extends Animal {
type SuitableFood = Grass
override def eat(food: SuitableFood) = {}
}
val bessy: Animal = new Cow
bessy eat new Fish
bessy eat new Cookies
我想知道在KOTLIN或JAVA中是否可以实现类似的目的?
答案 0 :(得分:1)
不确定要达到的目标。限制Cow
只吃Grass
吗?
我认为这可以通过泛型类型完成。
abstract class Food
open class Grass : Food()
class GreenGrass : Grass()
class Fish : Food()
abstract class Animal<T : Food> {
fun eat(food: T) { ... }
}
class Cow : Animal<Grass>()
class Bear : Animal<Fish>()
class Test {
fun test() {
val cow = Cow()
cow.eat(Grass()) // ok
cow.eat(GreenGrass()) // ok
cow.eat(Fish()) // not ok
val bear = Bear()
bear.eat(Fish()) // ok
bear.eat(Grass()) // not ok
}
}