scala类构造函数和抽象类型

Joh*_*ith 11 generics constructor scala abstract-type type-parameter

我想使用抽象类型而不是类型参数.

在我的泛型类构造函数中,我想要一个泛型类型的参数,但代码不能编译:

class SomeOtherClass(val s: S){
    type S
}
Run Code Online (Sandbox Code Playgroud)

scala编译器错误"找不到:类型S"

如果我使用类型参数而不是抽象类型,那么它的工作原理如下:

class SomeClass[T](val t: T){
    //...
}
Run Code Online (Sandbox Code Playgroud)

如果我想在构造函数中使用泛型参数,scala是否强制我使用类型参数而不是抽象类型?

还有另一种方法吗?

Kai*_*ito 2

在这种情况下,您几乎被迫使用泛型类型参数。您可以通过在类外部声明类型来解决这个问题,但随后您需要实例化包装器,然后实例化对象,它很快就会变得丑陋。

trait FooDef {
  type T
  class Foo(val x: T)
}
val ifd = new FooDef { type T = Int }
val ifoo = new ifd.Foo(5)
val sfd = new FooDef { type T = String }
val sfoo = new sfd.Foo("hi")
def intFoos(f: fd.Foo forSome { val fd: FooDef {type T = Int} }) = f.x + 1
Run Code Online (Sandbox Code Playgroud)