简体   繁体   中英

Scala: Use a Generic in Function Interface

I want to implement a function (as an object), something like:

object Add extends ((Int, Int) => Int) {
  def apply(a: Int, b: Int) = a + b
}

but I want to use Generics, because the Spark Dataset needs the Type like Dataset[Int] . How can I write a function with it? Because this one won't compile (unknown T):

object Something extends (Dataset[T] => Unit) {
 def apply(input Dataset[T]) = {
    ...
  }    
}

Edit:

Because the question appeared why I want to do this, in the end I want to write something like:

object Process {
  def doIt(config: Configuration) = {
    val step1 = Step1(config)
    val step2 = DoStep2(step1)
    Output(step2)
  }
}

It's only about how the source-code (should) look like. In a mathematical way you write a function like f(x) . With the possibility above I could write something like Step1(x) and it would look nearly similar to f(x) .

An object can not be generic.

But you can do something like this Instead.

object Something {
  def apply[T](ds: Dataset[T]) = {
    ...
  }
}

尝试

class Something[T] extends (Dataset[T] => Unit) ...

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