Scala Puzzle:强制执行两个函数参数的类型相同,并且都是给定类
发布时间:2020-12-16 19:17:06 所属栏目:安全 来源:网络整理
导读:我如何强制执行trickyMethod的参数在编译时是相同的,但同时也有常见的超类型Fruit? 换句话说,tricky.trickyMethod(新香蕉,新Apple)不应该编译. 我相信必须有一个简单的解决方案,但我只花了1个小时寻找答案,但仍然不知道:( 我尝试使用:隐式证据但我无法让它
|
我如何强制执行trickyMethod的参数在编译时是相同的,但同时也有常见的超类型Fruit?
换句话说,tricky.trickyMethod(新香蕉,新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 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))
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
