如何确保函数接收与当前对象相同的参数类型? [英] How do I make sure a function receives the same parameter type as the current object?
本文介绍了如何确保函数接收与当前对象相同的参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
abstract class A {
protected[this] type ThisType = this.type
protected[this] type OtherType = this.type
def assign(other: OtherType): ThisType
}
class B extends A {
def assign(other: OtherType): ThisType = ???
}
class C extends A {
def assign(other: OtherType): ThisType = ???
}
class D extends C {
def assign(other: OtherType): ThisType = ???
}
如何确保在assign
的B
对象中收到的另一个类型也是B
的对象.例如我该如何有效地写一些东西:
How do I make sure the other type received in assign
of and object of type B
is also B
. e.g. how can I write something effectively like:
def f1(p1: A, p2: A) = p1.assign(p2)
def f2[T <: A](p1: T, p2: T) = p1.assign(p2)
我遇到以下错误:
注意:实际上ThisType
和OtherType
应该相同,但是我将它们分开了,所以我可以尝试不同的选择.
NB: Actually ThisType
and OtherType
should be the same but I seperated them so I can try out different options.
推荐答案
abstract class A[T <: A[T]] {
def assign(other: T): T
}
class C extends A[C] {
override def assign(other: C): T = ???
}
def f1[T <: A[T]](p1: T, p2: T) = p1.assign(p2)
这篇关于如何确保函数接收与当前对象相同的参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文