斯卡拉的结构类型

Sri*_*vas 0 scala typeclass

如果我有这样的课程

class CanFlyType[T <: {type thing <: Bird}](t : T) {
  def flySpeed() = {
    println(t)
  }
}
Run Code Online (Sandbox Code Playgroud)

你可以在构造函数中传递什么来创建这个类?我试过传递这个

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)
Run Code Online (Sandbox Code Playgroud)

但是我收到了一个错误.我知道我们可以通过其他方式实现这一点,但我只是想知道你是否可以在结构类型方式中使用类型以及上面和

class CanFly1[T <: Bird1](bird : T) {
  def flySpeed() = {
    println(bird.flySpeed)
  }
}
Run Code Online (Sandbox Code Playgroud)

Nor*_*rwæ 5

当您指定时[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)
  }
}
Run Code Online (Sandbox Code Playgroud)

请注意,这可能不是您在实践中想要做的事情.你可能只想简单地约束你的CanFlyType[T <: Bird].