简体   繁体   中英

Scala : Generic method implicit parameter

I bumped into a code snippet and not able to make sense out of it. The snippet is:

  implicit val dummyVisit = Visit("", 1L, 1, 1, 1, 1L)
  implicit val dummyOrder = Order("", 1L, 1, 1, 1, 1L)

  def process[T](events : Array[T])(implicit t: T):Unit = {
    println(t)
    if(!events.isEmpty)
      t match {
        case r: Order => processOrder(events.asInstanceOf[Array[Order]])
        case r: Visit => processVisit(events.asInstanceOf[Array[Visit]]);
      }
  }

  def processOrder(arr: Array[Order]): Unit = { println(arr.size) }
  def processVisit(arr: Array[Visit]): Unit = { println(arr.size) }

The implicit variable t , requires the dummyVisit & dummyOrder to exist.

Question :

  1. Is this a right way of using implicit parameter ?

  2. Is there a better way for get the class-type of T , without using implicit parameter?

Capturing the type of an argument is one of the intended uses of implicit arguments.

Though I'd write something like this a bit differently:

import scala.reflect.ClassTag

// `sealed` ensures that no extra evidences can be defined elsewhere
sealed abstract class Evidence[T](implicit val tag: ClassTag[T])
object Evidence {
  implicit object visitEvidence extends Evidence[Visit]
  implicit object orderEvidence extends Evidence[Order]
}

def process[T](events: Array[T])(implicit ev: Evidence[T]) = {
  import ev.tag // import ClassTag[T] to allow matching on array element types
  events match {
    case Array() => // don't process empty arrays
    case arr: Array[Order] => processOrder(arr)
    case arr: Array[Visit] => processVisit(arr)
  }
}

This code avoids creating meaningless dummy instances, and typecasting with asInstanceOf .

A step further would be to capture the processing operation itself in the implicit argument and completely avoid the explicit match for every case. This is also known as typeclass pattern:

sealed trait ProcessArray[T] {
  def apply(arr: Array[T]): Unit
}
object ProcessArray {
  implicit object processVisitArray extends ProcessArray[Visit] {
    def apply(arr: Array[Visit]) = { println(arr.size) }
  }
  implicit object processOrderArray extends ProcessArray[Order] {
    def apply(arr: Array[Order]) = { println(arr.size) }
  }
}
def process[T](array: Array[T])(implicit proc: ProcessArray[T]) = {
  if (array.nonEmpty) proc(array)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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