gpt4 book ai didi

scala 类构造函数和抽象类型

转载 作者:行者123 更新时间:2023-12-04 02:23:36 24 4
gpt4 key购买 nike

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

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

class SomeOtherClass(val s: S){
type S
}

scala 编译器错误是“未找到:类型 S”

如果我使用类型参数而不是抽象类型,那么它可以工作:
class SomeClass[T](val t: T){
//...
}

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

有没有另一种方法可以做到这一点?

最佳答案

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

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

关于scala 类构造函数和抽象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11845058/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com