首页 > 解决方案 > 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)
  }
}

标签: scalatypeclass

解决方案


当您指定 时[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].


推荐阅读