【发布时间】:2019-11-09 03:35:39
【问题描述】:
关于scala中结构匹配的几个问题
问题 1) 在下面的代码中,我是否能够将 Bird 和 Plane 传递给 takeOff,因为 Bird 和 Plane 在结构上匹配起飞所需的对象 r?
import scala.language.reflectiveCalls
case class Bird (val name: String) extends Object {
def fly(height: Int):Unit = {println("bird fly")}
}
case class Plane (val callsign: String) extends Object {
def fly(height: Int):Unit = {println("plane fly")}
}
def takeoff(
runway: Int,
r: { val callsign: String; def fly(height: Int):Unit }) = {
println(r.callsign + " requests take-off on runway " + runway)
println(r.callsign + " is clear for take-off")
r.fly(1000)
}
val bird = new Bird("Polly the parrot"){ val callsign = name }
val a380 = new Plane("TZ-987")
takeoff(42, bird)
takeoff(89, a380)
问题 2) 什么是反射调用?我必须导入 scala.language.reflectiveCalls 否则我会收到警告 reflective access of structural type member value callsign should be enabled by making the implicit value scala.language.reflectiveCalls visible.
问题 3) 如何创建 Bird 如下:val bird = new Bird("Polly the parrot"){ val callsign = name }。不应该只是val bird = new Bird("Polly the parrot")。这是怎么编译的。
问题 3.1)。 bird 仍然是 Bird 类型,还是现在是其他类型,因为我已经通过了额外的 {...}
4) takeOff中的r是什么类型。
【问题讨论】: