【问题标题】:How avoid type repetition for inherited fields in Scala如何避免Scala中继承字段的类型重复
【发布时间】:2020-01-04 02:32:21
【问题描述】:

我开始缓慢地从 Java 迁移到 Scala 并面临一些问题。 其中之一是笨拙的构造函数参数。 我知道我无法避免它们,但至少我想介绍一些 像 C++ 这样的类型别名有 typename 可以在子类中使用。

case class A[E <: Throwable]
(
  mappers: Map[Class[_ :< Throwable], ExceptionMapper[_ <: Throwable]]
) {
}

case class B[CompletionException]
(
  mappers: Map[Class[_ :< Throwable], ExceptionMapper[_ <: Throwable]]
) extends A(mappers) {
}

所以在上面的示例中,mappers 字段的类型很糟糕,我只想在基类中输入一次。

【问题讨论】:

    标签: java scala types


    【解决方案1】:

    在 Scala 中你可以引入类型别名

    type M = Map[Class[_ <: Throwable], ExceptionMapper[_ <: Throwable]]
    
    class A[E <: Throwable]
    (
      mappers: M
    ) {
    }
    
    class B[CompletionException]
    (
      mappers: M
    ) extends A(mappers) {
    }
    

    顺便说一下,case 类不应该因为equals/hashCode 的问题而相互扩展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多