繁体   English   中英

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

[英]How to access a class's type parameter in Scala

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

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

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

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

我将一个Bar实例传递给另一个接受Foo子类的类,我想调用方法foo on 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)
}

你只需要一个

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

Foo[_]调用它是好的。

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

用特征中的“类型成员”替换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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM