You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中抽象类的ArrayBuffer能否容纳派生类实例?

Can an ArrayBuffer[Transformation] hold instances of its subclass Map?

当然没问题!这正是面向对象编程中多态特性的核心应用之一。

在Scala里,当你声明一个ArrayBuffer[Transformation]时,它不仅能存储Transformation的相关实例(不过因为它是抽象类,你根本没法直接实例化它),还能完美容纳所有继承自Transformation的子类实例——包括你定义的Map类。

先修正代码里的小问题

你写的Map类在调用父类构造时有点小错误,传参时不需要重复声明参数类型,修正后代码如下:

abstract class Transformation(tableName: List[String], operation: List[String], outputTable: String) {}

class Map(tableName: List[String], newColumn: String, operation: List[String], outputTable: String) 
  extends Transformation(tableName, operation, outputTable) {} // 去掉参数的类型声明

var transformationArray: ArrayBuffer[Transformation] = ArrayBuffer()

实际使用示例

现在你可以轻松把Map实例存入这个ArrayBuffer:

// 创建一个Map操作实例
val userMapOp = Map(
  List("user_info"), 
  "full_name", 
  List("concat(first_name, ' ', last_name)"), 
  "user_full_info"
)

// 添加到ArrayBuffer中
transformationArray += userMapOp

// 验证存储结果
transformationArray.foreach(op => println(s"Stored operation type: ${op.getClass.getSimpleName}"))
// 输出:Stored operation type: Map

拓展:调用子类独有逻辑

如果后续Map有自己的独有方法,你可以通过类型匹配来调用这些特定逻辑:

transformationArray.foreach {
  case mapOp: Map => println(s"This Map operation creates new column: ${mapOp.newColumn}")
  case _ => println("Other type of transformation")
}

内容的提问来源于stack exchange,提问作者Soumyadip Ghosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:13:34