【问题标题】:Share generic between traits在特征之间共享泛型
【发布时间】:2016-04-27 15:22:18
【问题描述】:

我有两个特点

trait Base[A]

trait SometimesUsedWithBase[A] {
    this: Base[A] =>
}

然后我将它们与类一起使用

class StringThing extends Base[String] with SometimesUsedWithBase[String]

如果我不必定义 SometimesUsedWithBase 的类型,那就太好了,而是它以某种方式理解它正在使用 Base 中定义的类型,因此它看起来像:

class StringThing extends Base[String] with SometimesUsedWithBase

这可能吗?

【问题讨论】:

    标签: scala generics types


    【解决方案1】:

    你应该可以做这样的事情。

    trait Base[A] {
      type BaseType = A
    }
    
    trait SometimesUsedWithBase {
      this: Base[_] =>
      def someFunction: BaseType
    }
    
    class StringThing extends Base[String] with SometimesUsedWithBase {
      def someFunction: String = ""
    }
    

    【讨论】:

    • 这对我来说非常有效,尤其是因为它们无论如何都绑在一起了。谢谢!
    • 显然,如果你向 someFunction 添加一个 BaseType 类型的参数,你会得到关于协变和逆变位置的错误..
    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2023-01-12
    • 1970-01-01
    • 2012-01-15
    • 2013-06-09
    相关资源
    最近更新 更多