scala - Scala,如何指定具有多个特征的函数参数?
问题描述
我有以下一段代码,我认为一旦你看到我的问题就会很明显。
trait hasId {
def id: String
}
trait hasCount {
def count: Int
}
case class Foo(id: String, count: Int) extends hasId with hasCount
// This is the function I want to write
def printData(data: hasId and hasCount): Unit = {
println(data.id + ": " data.count);
}
我应该如何声明函数签名?
解决方案
答案的解决方案是with
关键字,它用于您的含义and
。Terry Dactyl 写的泛型是一种可能的解决方案:
def printData[T <: hasId with hasCount](data: T): Unit = {
println(data.id + ": " + data.count)
}
另一个是使用type
别名with
:
type hasIdAndCount = hasId with hasCount
def printData(data: hasIdAndCount): Unit = {
println(data.id + ": " + data.count)
}
甚至直接:
def printData(data: hasId with hasCount): Unit = {
println(data.id + ": " + data.count)
}
推荐阅读
- ios - 我想使用来自 iOS 项目的标准 API 调用从 SF 获取数据
- php - 将数组传递给侦听器并获取更新的数组
- javascript - 在 jest 中获取“您正在尝试在 Jest 环境被拆除后导入文件”和“instanceof 的右侧不可调用”
- exception - 无法在 codeigniter 4 中插入数据
- c - 如何让报警器安全?
- jenkins - 即使通过 pip install mkdocs 安装后,mkdocs 也无法在 Jenkins 中工作
- sql-server - Sql server 查找字符串的出现次数
- node.js - DiscordJS 嵌入未正确添加字段
- python - 正则表达式忽略字符串中的数字(python)
- rebol - 如何通过红色/rebol中的“foreach”修改块的每个元素