1

X で渡すオブジェクトのタイプに応じて、apply メソッドを使用する必要があります。使用する修飾子 (Y または Z) を指定できます。次のような「次の」関数を使用する構文が必要です。

(object of type B) following Y

また

(object of type C) following Z

コードは次のようになります。

trait A 
{
    def following(modifier: X) = modifier(this)
}
case class B() extends A{}
case class C() extends A{}
trait X {}
object Y extends X
{
    apply(obj: B):B = {}
    apply(obj: C):C = {}
}
object Z extends X
{
    apply(obj: B):B = {}
    apply(obj: C):C = {}
}

コンパイラは、「次の」関数を実装した行でエラーを出します。私は何を間違っていますか?

4

2 に答える 2

3

あなたが望むのは次のようなものだと思います:

    trait X {
        def apply[T](obj: T): T
    }

    trait A {
        def following(modifier: X) = modifier(this)
    }

    case class B() extends A
    case class C() extends A

    object Y extends X {
        override def apply[B](obj: B): B = { obj }
        override def apply[C](obj: C): C = { obj }
    }

    object Z extends X {
        override def apply[B](obj: B): B = { obj }
        override def apply[C](obj: C): C = { obj }
    }

残念ながら、オーバーライドされた apply メソッドを 2 つ持つことはできないと思います。そのため、コンパイルされません。これが可能であれば、私も喜んでお知らせします。現時点でできることは、パターン マッチングで 1 つの apply メソッドを使用することです。

    trait X {
        def apply[T](obj: T): T
    }

    trait A {
        def following(modifier: X) = modifier(this)
    }

    case class B() extends A
    case class C() extends A

    object Y extends X {
        override def apply[T](obj: T): T = {
            obj match {
                case o: B => obj
                case o: C => obj
            }
        }
    }

    object Z extends X {
        override def apply[T](obj: T): T = {
            obj match {
                case o: B => obj
                case o: C => obj
            }
        }
    }

まったく同じ効果 (構文を含む) を別の方法で得ることもできます。私の意見では、はるかにクリーンで理解しやすいです。

    sealed trait X
    case class Y() extends X
    case class Z() extends X

    trait A[T] {
        def following(modifier: X): T
    }

    case class B() extends A[B] {
        override def following(modifier: X) = modifier match {
            case o: Y => this
            case o: Z => this
        }
    }

    case class C() extends A[C] {
        override def following(modifier: X) = modifier match {
            case o: Y => this
            case o: Z => this
        }
    }
于 2013-10-30T14:47:29.887 に答える