gpt4 book ai didi

斯卡拉拼图 : enforcing that two function arguments are of the same type AND both are a subtype of a given class

转载 作者:行者123 更新时间:2023-12-04 10:18:22 24 4
gpt4 key购买 nike

我如何强制执行该操作 trickyMethod的参数在编译时相同,但同时也有共同的父类(super class)型 Fruit ?

换句话说,tricky.trickyMethod(new Banana,new Apple)不应该编译。

我相信一定有一个简单的解决方案,但我只花了 1 小时寻找答案,但仍然不知道:(

我尝试使用 <:< 隐含证据,但我无法让它发挥作用。

class Fruit
class Apple extends Fruit
class Banana extends Fruit

class TrickyClass[T<:Fruit]{
def trickyMethod(p1:T,p2:T)= println("I am tricky to solve!")
}

object TypeInferenceQuestion extends App{
val tricky=new TrickyClass[Fruit]()
tricky.trickyMethod(new Apple,new Apple) //this should be OK
tricky.trickyMethod(new Banana,new Banana) //this should be OK
tricky.trickyMethod(new Banana,new Apple) //this should NOT compile

}

编辑 :

谢谢你的回答!

跟进(更一般的)问题:

第二个示例是第一个示例的更一般情况。
class Fruit

class Apple extends Fruit
class Banana extends Fruit

class TrickyClass[T]{
def trickyMethod[S<:T](p1:S,p2:S)= println("I am tricky to solve!")
}

object TypeInferenceQuestion extends App{
val tricky=new TrickyClass[Fruit]()
tricky.trickyMethod(new Apple,new Apple) //this should be OK
tricky.trickyMethod(new Banana,new Banana) //this should be OK
tricky.trickyMethod(new Banana,new Apple) //this should NOT compile

}

最佳答案

你可以这样做:

class Tricky[T] {
def trickyMethod[S1<:T,S2<:T](s1:S1,s2:S2)(implicit ev: S1=:=S2) = println()
}


scala> val t = new Tricky[Seq[Int]]
t: Tricky[Seq[Int]] = Tricky@2e585191

scala> t.trickyMethod(List(1),List(1))
//OK

scala> t.trickyMethod(List(1),Seq(1))
<console>:10: error: Cannot prove that List[Int] =:= Seq[Int].
t.trickyMethod(List(1),Seq(1))

关于斯卡拉拼图 : enforcing that two function arguments are of the same type AND both are a subtype of a given class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22383015/

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