如何定义方法返回此结构类型

时间:2016-02-24 11:18:54

标签: java scala structural-typing

我有一些Builder来自库,源代码是用Java自动生成的,超出了我的控制范围。这些Builder彼此不相关,但它们有许多方法在结构上完全相同。

package a.b

public class Builder {
    public Builder setA(xxx) {}
    public Builder setB(yyy) {}
}

package a.c

public class Builder {
    public Builder setA(xxx) {}
    public Builder setB(yyy) {}
}

使用Scala的结构类型,如何为自己返回构建器?

type StructurallyBuilder = {
    def setA(xxx): StructurallyBuilder
    def setB(yyy): StructurallyBuilder
}

当我想在StructurallyBuilder上使用setA和setB时,编译器会抱怨它无法解析。

3 个答案:

答案 0 :(得分:4)

这不是很简单,但我相信您可以使用F-bounded polymorphism来实现这一目标:

type StructurallyBuilder[F <: StructurallyBuilder[F]] = {
  def setA(xxx: Int): F
  def setB(yyy: Int): F
}

在定义使用这些构建器的类或方法时,必须保留此复杂签名。例如:

def setA[T <: StructurallyBuilder[T]](
  xxx: Int, 
  builder: StructurallyBuilder[T]
): T = builder.setA(xxx)

但似乎你可以正常使用这些方法:

val bld: a.c.Builder = setA(10, new a.c.Builder())

答案 1 :(得分:1)

您可以使实际构建器成为结构类型的类型参数:

import scala.language.reflectiveCalls
import scala.language.existentials

type StructurallyBuilder[T <: AnyRef] = AnyRef {
  def setA(xxx): T
  def setB(yyy): T
}

这是我写的一个小测试,证明你可以使用它来传递任何使用&#39; StructurallyBuilder&#39;作为参数类型:

import scala.language.reflectiveCalls
import scala.language.existentials

type StructurallyBuilder[T <: AnyRef] = AnyRef {
  def setA(a: Int): T
  def setB(b: String): T
}


class Builder1 {
  var a: Int = _
  var b: String = _

  def setA(a: Int): Builder1 = {
    this.a = a
    this
  }

  def setB(b: String): Builder1 = {
    this.b = b
    this
  }
}

val builder: StructurallyBuilder[_] = new Builder1

val b2 = builder.setA(1)
val b3 = builder.setB("B")

val builder2 = new Builder1

def test(builder: StructurallyBuilder[_]): String = {
  builder.toString
}

val t2 = test(builder2) |-> t2: String = Builder1@7a067558

答案 2 :(得分:0)

为什么不使用this.type?

type StructurallyBuilder = {
    def setA(x: Int): this.type
    def setB(y: Double): this.type
}

此类用法示例:

object App
{

  class A {
    def setA(x: Int): this.type = { this }
    def setB(y: Double): this.type = { this }
  }

  type StructurallyBuilder = {
    def setA(x: Int): this.type
    def setB(y: Double): this.type
  }


  def main(args: Array[String]):Unit =
  {
    val a = new A()
    if (a.isInstanceOf[StructurallyBuilder]) {
       System.out.println("qqq")
    }
    System.out.println(a)
   }

}

然后,尝试运行:

[info] Running X.App 
qqq
X.App$A@8f59676