如何在Scala中访问类的类型参数

时间:2014-05-25 18:32:32

标签: scala types

我有一个类型参数化的抽象类,它包含一个val和一个都使用其类型参数

的方法
abstract class Foo[T](val state: T){
  def foo(arg: T){
    ...
  }
}

我还有一个扩展这个抽象类的类,它提供了类型参数和state的值

class Bar(myNumber: Int) extends Foo[Int](myNumber){
   ...
}

我将Bar的实例传递给另一个接受Foo子类的类,我想在foo上调用方法state,但是我遇到麻烦:

class Baz(val f: Foo[_]){
    f.foo(f.state)
}

这给出了错误:

<console>:8: error: type mismatch;
 found   : Baz.this.f.state.type (with underlying type _$1)
 required: _$1
         f.foo(f.state)

有没有办法让Baz知道Bar的类型参数,以便正确编译?或者甚至是我想做什么?

修改

为了澄清,我有许多类似于Bar的类,它们扩展Foo并提供它们自己的类型参数,状态和foo的实现。我希望我的库的用户能够将其中任何一个传递给Baz,而不必担心类型参数T,因为它只是Foo的每个子类的实现细节。

所以我强烈不愿意这样做:

class Baz[T](val f: Foo[T]){
  f.foo(f.state)
}

2 个答案:

答案 0 :(得分:2)

你只需要一个

def fooOnState[T](ft: Foo[T]) = ft.foo(ft.state)

Foo[_]调用它是可以的。

但是,大多数时候最好避免存在,但这取决于你的真实代码。

答案 1 :(得分:0)

使用特征中的“类型成员”替换type参数可以编写适用于所有状态类型的通用代码,但代价是在每个子类中指定类型成员有点冗长:

trait Foo {
  type StateT  // this is the "type member"
  val state: StateT
  def foo(arg: StateT): Unit
}

class Bar(myNumber: Int) extends Foo {
  type StateT = Int     // this is the verbose part
  override val state = myNumber  // this, too
  override def foo(arg: StateT) { /* something specific here */ }
}

class Baz(val f: Foo) {
  f.foo(f.state)  // generic code, works on any Foo subclass
}