在Scala中访问类外部的类型成员

Pek*_*ila 7 types type-systems programming-languages scala

我试图了解Scala中的类型成员.我写了一个简单的例子,试图解释我的问题.

首先,我为类型创建了两个类:

class BaseclassForTypes
class OwnType extends BaseclassForTypes
Run Code Online (Sandbox Code Playgroud)

然后,我在trait中定义了一个抽象类型成员,然后在一个concerete类中定义了类型成员:

trait ScalaTypesTest {
  type T <: BaseclassForTypes

  def returnType: T
}

class ScalaTypesTestImpl extends ScalaTypesTest {
  type T = OwnType

  override def returnType: T = {
    new T
  }
} 
Run Code Online (Sandbox Code Playgroud)

然后,我想访问类型成员(是的,这里不需要类型,但这解释了我的问题).两个例子都有效.

解决方案1.声明类型,但问题是它不使用类型成员并且类型信息是重复的(调用者和被调用者).

val typeTest = new ScalaTypesTestImpl
val typeObject:OwnType = typeTest.returnType // declare the type second time here
true must beTrue
Run Code Online (Sandbox Code Playgroud)

解决方案2.初始化类并通过对象使用类型.我不喜欢这个,因为这个类需要初始化

val typeTest = new ScalaTypesTestImpl
val typeObject:typeTest.T = typeTest.returnType // through an instance
true must beTrue
Run Code Online (Sandbox Code Playgroud)

那么,有没有更好的方法来实现这一点,或者类型成员是否只用于类的内部实现?

Yar*_*ena 7

您可以使用ScalaTypesTestImpl#T而不是typeTest.T,或

val typeTest:ScalaTypesTest = new ScalaTypesTestImpl
val typeObject:ScalaTypesTest#T = typeTest.returnType
Run Code Online (Sandbox Code Playgroud)