简体   繁体   中英

Extending a Function1 in Scala

In few examples, I have seen that an object or a class extends Function1 .

Eg object Cash extends (CashProduct => String) in Hidden features of Scala

(I suppose A => B means Function1 )

What it the benefit of extending a Function1 ?

The full example of what you provided:

object Cash extends (CashProduct => String) {
  def apply(p: CashProduct) = p.currency.name + "="

  def unapply(s: String)(implicit ps: ProductService): Option[CashProduct] = {
    if (s.endsWith("=") 
      Some(ps.findCash(s.substring(0,3))) 
    else None
  }
}

Shows that OP wanted to gain the syntactical benefit of the apply method, which allows your to create an instance calling Cash(...) .

But why would you really want to extend a function? Lets look at a better case perhaps, List[T] .

If we look up the long inheritance hierarchy, we'll see that:

trait Seq[+A] extends PartialFunction[Int, A]  

Hmm, why does Seq extend PartialFunction[Int, A] (which in turns inherits Function1[A, B] ? Because if we think about it, if I pass a List[A] an Int , representing the index of the element I'm seeking , it will (not efficiently) return me the element at that given index (if present).

The benefit of extending Function1 as compared to just defining apply is just that you can pass this object where a Function1 is expected. Eg

val products: List[CashProduct] = ...
products.map(Cash)

Without the extends it would have to be written as

val products: List[CashProduct] = ...
products.map(Cash(_)) 
// or products.map(Cash.apply)

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