[英]A more functional way to write this?
我在想什么,我寫了這個特質與擴展它兩個階級,可能包含這些其他類:
sealed trait MainObj
case object subObj1 extends mainObj
case Object subObj2 extends mainObj
case class AnotherClass(val mo: Option[MainObj], val amount: Int)
現在,讓我們說,我想寫的添加量在兩個功能AnotherClass
對象,但只有當可選MainObj
里面每個人都是一樣的類型。 像只添加如果兩者都subObj1
。
所以我可以做這樣的事情:
def add(one: AnotherClass, two: AnotherClass): AnotherClass = one. mo, two.mo match {
case (Some(x), Some(y)) if i and x are the same class => return a `AnotherClass` with the two integers added from `one` and `two`
etc..
我想知道是否有這樣做的另一種方式? 我不知道這是否是這樣做的,或者是否有一個更簡潔的方式“功能”的方式?
我問,因為基本上我可以多寫一些方法,如subtract
, multiply
,等...和我有一些很常見的代碼。
我可以提取公共代碼,寫一個函數,只是需要兩個subObj
S和操作,然后應用在兩個對象的操作,但只有抽象出常見的操作,可能會匹配部分的主要模式有不同的書面可能會被認為更簡潔(因為缺少更好的詞)?
只需將'add'方法添加到case類:
sealed trait MainObj
case object SubObj1 extends MainObj
case object SubObj2 extends MainObj
case class AnotherClass(val mo: Option[MainObj], val amount: Int){
def add(that:AnotherClass):AnotherClass = {
if (that.mo == this.mo)
this.copy(amount = this.amount + 1)
else
this
}
}
val x = AnotherClass(Some(SubObj1), 1)
val y = AnotherClass(Some(SubObj1), 1)
val z = AnotherClass(Some(SubObj2), 1)
scala> x add y
res5: AnotherClass = AnotherClass(Some(SubObj1),2)
scala> x add z
res6: AnotherClass = AnotherClass(Some(SubObj1),1)
scala> val l = List(x,y,z)
l.reduce ( _ add _)
res7: AnotherClass = AnotherClass(Some(SubObj1),2)
val mo = two.mo
one match {
case AnoterClass(`mo`, am) =>
one.copy(amount = am + two.amount)
case _ => ???
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.