scala - scala pass a variable list of parameters and types to a function
问题描述
How can I pass a variable list of parameters and types to a function?
I.e. the depicted approach which is using pattern matching seems a bit clumsy.
In an trait
the function foo
is defined. However in concrete implementations a different subtype (with additional fields should be used). Is there a cleaner approach than using pattern matching?
def foo[T <: MyBaseConfiguration](config: T) = {
println("do smething")
println(config.configValue)
}
override def foo[T <: MyBaseConfiguration](config: T) = {
config match {
case c: MyOtherConfiguration => {
println("do smething else")
println(c.configValue)
println(c.otherValue)
}
}
}
trait MyBaseConfiguration {
def configValue: String
}
class MyOtherConfiguration extends MyBaseConfiguration {
val otherValue = 1234
override def configValue = "abcd"
}
edit
Basicylly, I just want to say * there is a function f
with a defined return value TReturn
but be agnostic to input parameters.
Still, I need to be able to use / access them during the execution of f
.
解决方案
你要求做的是这样的:
trait Foo {
def foo[T <: MyBaseConfiguration](config: T) = {
println("do smething")
println(config.configValue)
}
}
class Foo2 extends Foo {
override def foo[T <: MyOtherConfiguration](c: T) = {
println("do smething else")
println(c.configValue)
println(c.otherValue)
}
}
但是,这不起作用,因为它破坏了类型安全。考虑以下:
class MyThirdConfiguration extends MyBaseConfiguration {...}
val foo2: Foo = new Foo2
val cfg: MyBaseConfiguration = new MyThirdConfiguration
foo2.foo(cfg)
foo2
是一个实例,Foo2
但看起来像一个Foo
. cfg
是一个实例,MyThirdConfiguration
但看起来像MyBaseConfiguration
. 即使类型匹配,也可以使用没有且没有额外字段的对象进行foo2.foo(cfg)
调用。Foo2.foo
MyOtherConfiguration
请注意,Foo2.foo
可以将其定义为采用超类,MyBaseConfiguration
因为这不会破坏类型安全。
另请注意,重载函数的结果类型以相反的方式工作。您可以返回基函数返回的类型的子类,但不能返回超类,因为前者是类型安全的,而后者不是。
推荐阅读
- parse-platform - 如果不存在,则解析模式添加字段
- numpy - 在 Keras 指标之间共享操作结果
- excel - 将工作表复制并粘贴到另一个工作簿,然后返回到您复制的工作簿
- python - 在 Mac 上使用 IDLE 安装 glob2
- swiftui - SwiftUI 在视图之间切换
- python - Python3 以编程方式将字符串转换为原始字符串
- python - 当有多个同名对象时更新 JSON - Python
- azure-devops - 如何找出:拉取请求是否涵盖给定分支中的所有提交?
- c# - 我可以在方法结束时安全地删除 await Task.CompletedTask 调用吗?
- c# - C# UWP 中的 TouchMajor 和 TouchMinor