繁体   English   中英

一种更实用的方式编写此代码?

[英]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..

我想知道是否有这样做的另一种方式? 我不知道这是否是这样做的,或者是否有一个更简洁的方式“功能”的方式?

我问,因为基本上我可以多写一些方法,如subtractmultiply ,等...和我有一些很常见的代码。

我可以提取公共代码,写一个函数,只是需要两个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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM