入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

mkString优化以及超过22字段在scala2.10中的一个小需求

创建时间:2016-02-25 投稿人: 浏览次数:1731

今天一个朋友让我给优化一段代码,他设计了一个很庞大的类,有40个字段,由于22 limit的缘故,他实现了Product特质,并且实现了那些方法,可是他在重写toString的时候写的很java,于是我们进行了一下优化:

  override def toString = {
    val sb = new StringBuilder("MkStringInClass:[")
    for (i ← 0 until productArity) {
      if (i > 0)
        sb.append(",")
      sb.append(productElement(i) match {
        case Some(x) ⇒ x
        case t ⇒ t
      })
    }
    sb.append("]")
    sb.toString
  }

原方法很java,用一个StringBuider在实现一个拼接,我觉得可以用mkString,所以进行了改进:


    override def toString = s"${
      (for (i ← 0 until productArity) yield productElement(i) match {
        case Some(t) ⇒ t
        case t ⇒ t
      }).mkString("MakeStringClass:[", ",", "]")
    }"

这样看起来清爽多了,主要就是用mkString去做了原来StringBuffer干的活

 def mkString(start : scala.Predef.String, sep : scala.Predef.String, end : scala.Predef.String) : scala.Predef.String = { /* compiled code */ }
  def mkString(sep : scala.Predef.String) : scala.Predef.String = { /* compiled code */ }
  def mkString : scala.Predef.String = { /* compiled code */ }

完整代码:

package com.linewell.other

import scala.util.{Failure, Success, Try}

/**
  * Created by ctao on 16-2-25.
  */
class MakeStringInClass(
                         id: Int,
                         name: String,
                         age: Int,
                         location: Option[String]
                       ) extends Product with Serializable {
  override def productElement(n: Int): Any = n match {
    case 0 ⇒ id
    case 1 ⇒ name
    case 2 ⇒ age
    case 3 ⇒ location
    case _ ⇒ throw new IndexOutOfBoundsException(n.toString)
  }

  override def productArity: Int = 4

  override def canEqual(that: Any): Boolean = that.isInstanceOf[MakeStringInClass]

    override def toString = s"${
      (for (i ← 0 until productArity) yield productElement(i) match {
        case Some(t) ⇒ t
        case t ⇒ t
      }).mkString("MakeStringClass:[", ",", "]")
    }"

/*  override def toString = {
    val sb = new StringBuilder("MkStringInClass:[")
    for (i ← 0 until productArity) {
      if (i > 0)
        sb.append(",")
      sb.append(productElement(i) match {
        case Some(x) ⇒ x
        case t ⇒ t
      })
    }
    sb.append("]")
    sb.toString
  }*/
}

object MakeStringInClass {

  def apply(str: String): Option[MakeStringInClass] = {
    val params = str.split(" ")
    Try {
      new MakeStringInClass(params(0).toInt, params(1), params(2).toInt, Some(params(3)))
    } match {
      case Success(x) ⇒ Some(x)
      case Failure(e) ⇒ None
    }
  }
}

我这边就只是写了几个字段意思了下,哈哈
他的源代码:

package xxx.xx.xxx
class Order(val id: Option[String]=None ,val orderId: Option[String]=None ,val tradeId: Option[String]=None ,val platformCode: Option[String]=None ,
             val platformName: Option[String]=None ,val orderType: Option[String]=None ,val storeCode: Option[String]=None ,val storeName: Option[String]=None ,
             val tradeFrom: Option[String]=None ,val createdAt: Option[String]=None ,val paymentAt: Option[String]=None , val deliveryAt: Option[String]=None ,
             val finishedAt: Option[String]=None ,val isCod: Option[Char]=None , val isInvoice: Option[Char]=None ,val price: Option[Double]=None ,
             val payment: Option[Double]=None ,val quantity: Option[Int]=None ,val promotion: Option[Double]=None ,val expressFee: Option[Double]=None ,
             val orderStatus: Option[String]=None ,val omsOrderStatus: Option[String]=None ,val deliveryStatus: Option[String]=None , val isOutOfStock: Option[Char]=None ,
             val isBag: Option[Char]=None ,val bagDescription: Option[String]=None ,val buyerAccount: Option[String]=None , val buyerNick: Option[String]=None ,
             val buyerEmail: Option[String]=None ,val buyerMessage: Option[String]=None ,val consignee: Option[String]=None , val mobile: Option[String]=None ,
             val address: Option[String]=None ,val fullAddress: Option[String]=None ,val sellerNick: Option[String]=None ,val sellerMessage: Option[String]=None ,
             val refuseReason: Option[String]=None ,val refundStatus: Option[String]=None ,val refundFinished: Option[String]=None
)extends Product  with Serializable{

  override def canEqual(that: Any): Boolean = that.isInstanceOf[Order]

  override def productArity: Int = 39

  override def toString(): String ={
    s"Order[${(for(i<- 0 until productArity) yield productElement(i) match{case Some(x)=>x case t=>t}).mkString(",")}]"
  }

  @throws(classOf[IndexOutOfBoundsException])
  override def productElement(n: Int) = n match {
    case 0 => id
    case 1 => orderId
    case 2 => tradeId
    case 3 => platformCode
    case 4 => platformName
    case 5 => orderType
    case 6 => storeCode
    case 7 => storeName
    case 8 => tradeFrom
    case 9 => createdAt
    case 10 => paymentAt
    case 11 => deliveryAt
    case 12 => finishedAt
    case 13 => isCod
    case 14 => isInvoice
    case 15 => price
    case 16 => payment
    case 17 => quantity
    case 18 => promotion
    case 19 => expressFee
    case 20 => orderStatus
    case 21 => omsOrderStatus
    case 22 => deliveryStatus
    case 23 => isOutOfStock
    case 24 => isBag
    case 25 => bagDescription
    case 26 => buyerAccount
    case 27 => buyerNick
    case 28 => buyerEmail
    case 29 => buyerMessage
    case 30 => consignee
    case 31 => mobile
    case 32 => address
    case 33 => fullAddress
    case 34 => sellerNick
    case 35 => sellerMessage
    case 36 => refuseReason
    case 37 => refundStatus
    case 38 => refundFinished
    case _ => throw new IndexOutOfBoundsException(n.toString())
  }
}

my github

阅读更多
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。