scala - scala中的结构类型
问题描述
如果我有这样的课
class CanFlyType[T <: {type thing <: Bird}](t : T) {
def flySpeed() = {
println(t)
}
}
你可以在构造函数中传递什么来创建这个类?我试着通过这个
class Species
class Animal extends Species
class Tiger extends Animal
abstract class Bird (name : String) extends Species {
val birdName = name
val flySpeed : Int
}
class Sparrow(name : String) extends Bird(name) {
val flySpeed = 30
}
val sparrow : Bird1 = new Sparrow("Robbin")
val canFly = new CanFlyType(sparrow)
但我得到一个错误。我知道我们可以通过其他方式实现这一点,但我只想知道您是否可以以结构类型的方式使用类型以及上述和之间的区别
class CanFly1[T <: Bird1](bird : T) {
def flySpeed() = {
println(bird.flySpeed)
}
}
解决方案
当您指定 时[T <: {type thing <: Bird}]
,您是在告诉编译器查找具有名为 thing 的类型成员的类型,该类型成员本身必须是 的子类Bird
。
以下解决了该问题:
class Species
class Animal extends Species
class Tiger extends Animal
abstract class Bird (name : String) extends Species {
val birdName = name
val flySpeed : Int
}
class Sparrow(name : String) extends Bird(name) {
type thing = this.type
val flySpeed = 30
}
val sparrow : Sparrow = new Sparrow("Robbin")
val canFly = new CanFlyType(sparrow)
class CanFlyType[T <: {type thing <: Bird}](t : T) {
def flySpeed() = {
println(t)
}
}
请注意,这可能不是您在实践中想要做的。您可能希望简单地限制您的CanFlyType[T <: Bird]
.
推荐阅读
- ios - 如何将触摸事件从页面视图控制器传递到容器控制器?
- docker - Docker 无法连接到本地主机
- javascript - Add class for the clicked button and remove class from siblings
- spring-boot - Spring Boot - 无法配置数据源:未指定“url”属性并且无法配置嵌入式数据源
- javascript - 如何更改角矩语言环境?
- laravel - 无法在 laravel 中运行迁移
- excel - Excel / Google 工作表 - 条件 IF .. 但是
- python-3.x - 如何在 Python 中对数字进行舍入(逗号后有多个数字)
- javascript - 将书籍对象插入书籍数组
- python - 在图像数组中的点周围显示 3x3 框中的点