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

标签: scalafunctiongenericstype-parameter

解决方案


你要求做的是这样的:

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.fooMyOtherConfiguration

请注意,Foo2.foo可以将其定义为采用超类MyBaseConfiguration因为这不会破坏类型安全。

另请注意,重载函数的结果类型以相反的方式工作。您可以返回基函数返回的类型的子类,但不能返回超类,因为前者是类型安全的,而后者不是。


推荐阅读