Search code examples
scalawildcardtype-parameter

How can I cast an object as parameter of Function1[Array[_], Unit] inScala


class MyClass(functions: Seq[Function1[Array[_], Unit]) {
  def foo(parametersForEachFunction: Seq[Array[_]]) {
    assert(functions.size == parametersForEachFunction.size)
    for ((function, parameter) <- functions zip parametersForEachFunction) {
      // Assume each parameter is suitable for the funcition
      // What type parameter I should wrote in asInstanceOf?
      function(parameter.asInstanceOf[ ?????? ])
    }
  }
}

I know an asInstanceOf is required here, but I don't know what type parameter I should wrote in asInstanceOf.


Solution

  • If you have to cast, you are doing it wrong. Whenever you think you should cast something, rollback and try something else. There are exceptions -- if the documentation of something explicitly tell you to cast, well, you have to cast. But don't count on you have such an exception: you probably don't.

    As in this case.

    scala> class MyClass(functions: Seq[Function1[Array[_], Unit]]) {
         |   def foo(parametersForEachFunction: Seq[Array[_]]) {
         |     assert(functions.size == parametersForEachFunction.size)
         |     for ((function, parameter) <- functions zip parametersForEachFunction) {
         |       function(parameter)
         |     }
         |   }
         | }
    defined class MyClass