简体   繁体   English

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

[英]A more functional way to write this?

I was thinking about something, I wrote this trait with two classes extending it and another class that may contain them: 我在想什么,我写了这个特质与扩展它两个阶级,可能包含这些其他类:

sealed trait MainObj
case object subObj1 extends mainObj
case Object subObj2 extends mainObj

case class AnotherClass(val mo: Option[MainObj], val amount: Int)

Now let's say I wanted to write a function that added the amounts in two AnotherClass objects but only if the optional MainObj inside each of them were the same type. 现在,让我们说,我想写的添加量在两个功能AnotherClass对象,但只有当可选MainObj里面每个人都是一样的类型。 Like only add if both are subObj1 . 像只添加如果两者都subObj1

So I could do something like this: 所以我可以做这样的事情:

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..

I wondered whether there was another way of doing this? 我想知道是否有这样做的另一种方式? I don't know whether this is a "functional" way of doing it or whether there is a less verbose way? 我不知道这是否是这样做的,或者是否有一个更简洁的方式“功能”的方式?

I ask because essentially I could write some more methods like subtract , multiply , etc ... and I have some very common code. 我问,因为基本上我可以多写一些方法,如subtractmultiply ,等...和我有一些很常见的代码。

I could extract that common code and write a function that simply takes two of the subObj s and an operation and then apply that operation on the two objects, but that only abstracts out the common operation, could the main pattern matching part be written differently that may be considered more concise(for lack of a better word)? 我可以提取公共代码,写一个函数,只是需要两个subObj S和操作,然后应用在两个对象的操作,但只有抽象出常见的操作,可能会匹配部分的主要模式有不同的书面可能会被认为更简洁(因为缺少更好的词)?

Just add the 'add' method to the case class : 只需将'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