gpt4 book ai didi

scala - 为什么删除后 "Banana with Cream"和 "Banana"的类型一样?如何修复?

转载 作者:行者123 更新时间:2023-12-01 09:48:07 24 4
gpt4 key购买 nike

我想要根据标记特征(如 Cream)绑定(bind)不同的方法(在编译时!)。如何实现?

我下面的解决方案无法编译。

如何修复?

class Apple
class Banana
trait Cream

object HasOverloadedMethods
{
def method(p:Apple)=println("Apple")
def method(p:Banana)=println("Banana")
def method(p:Banana with Cream)=println("Banana with Cream")
}

object Question extends App{
HasOverloadedMethods.method(new Apple())
HasOverloadedMethods.method(new Banana())
HasOverloadedMethods.method(new Banana() with Cream)
}

错误:

double definition:
method method:(p: Banana with Cream)Unit and
method method:(p: Banana)Unit at line 9
have same type after erasure: (p: Banana)Unit
def method(p:Banana with Cream)=println("Banana with Cream")
^

最佳答案

不幸的是,你不能那样修复它,因为 JVM 不知道混合类型(并且 method(x: Banana with Cream) 的字节码签名因此只是 method (x: 香蕉)).

您有几个选择,它们都有各自的缺点。

  1. 只服用奶油。这会让你失去 Banana
  2. 创建一个BananaWithCream 特征。这会使您的层次结构困惑。
  3. 使用类型类:

    def method[T : MethImpl](x: T) = implicitly[MethImpl[T]].impl(x)

    trait MethImpl[T] {
    def impl(x: T): Unit
    }

    trait LowPrioMethImpl {
    implicit object BananaImpl extends MethImpl[Banana] {
    def impl(x: Banana) = println("Banana")
    }
    }

    object MethImpl extends LowPrioMethImpl {
    implicit object AppleImpl extends MethImpl[Apple] {
    def impl(x: Apple) = println("Apple")
    }

    implicit object BananaWithCreamImpl extends MethImpl[Banana with Cream] {
    def impl(x: Banana with Cream) = println("Banana with Cream")
    }
    }

    现在您可以:

    method(new Banana) // > Banana
    method(new Banana with Cream) // > Banana with Cream
    method(new Apple) // > Apple

    method("adsf") // error: Could not find implicit value ...

    缺点显然是此解决方案引入的困惑。

关于scala - 为什么删除后 "Banana with Cream"和 "Banana"的类型一样?如何修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22422467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com