2012-03-01 8 views
0

は、私はこのようないくつかのコードがあります:

case class FunctionCommand[A](function: Function1[Array[A], Unit]) 

class MyClass(commands: List[FunctionCommand[_]]) { 
    def foo(parametersForEachFunction: Seq[Array[_]]) { 
    assert(commands.size == parametersForEachFunction.size) 
    for ((command, parameter) <- commands zip parametersForEachFunction) { 
     command.function(parameter) 
    } 
    } 
} 

をそして、それはコンパイルされません:

MyClass.scala:7: type mismatch; 
found : Array[(some other)_0(in value $anonfun)] where type (some other)_0(in value $anonfun) 
required: Array[_0(in value $anonfun)] where type _0(in value $anonfun) 
     command.function(parameter) 
         ^

私はArray[(some other)_0(in value $anonfun)]があるのだろうか。コンパイルできるようにcommand.function(parameter.asInstanceOf[????])のようなものを書くことはできますか?

回避策があります。私はにcommand.function(parameter)を置き換える:

def forceInvoke[A](command: FunctionCommand[A], parameter: Any) { 
    command.function(parameter.asInstanceOf[A]) 
} 
forceInvoke(command, parameter) 

そして、それはコンパイルされます。

しかし、parameterを実行時に正式に正しい型にキャストする方法があるかどうかはまだ分かります。

+0

あなたを使用してください回避策。あなたの目標は、Scalaタイプのシステムがあなたが望む柔軟性を得る方法です。 – huynhjl

+0

あなたはタイプを失って元に戻したくありません。型が必要な場合は、どこでも '_'を使用しないでください。異なる既知の型のリストが必要な場合は、 'HList'が必要です。その場合は[shapeless](https://github.com/milessabin/shapeless)を参照してください。 –

+1

私はエンジニアであり、数学者ではありません。キーボードには「λ」、「ℤ」、「⊤」などはありません。 –

答えて

1

それはこのようにそれを書くことは十分だ:

for ((command: FunctionCommand[_], parameter) <- commands zip parametersForEachFunction) { 
    command.function(parameter) 
} 
+1

この方法はScala 2.9.1でもOKですが、Scala 2.10-M2の警告が発生します。 'MyClass.scala:6:ツリー内に存在するSkolem型のエラーから回復します。 temp3.function() 型[_ $ 1] =>ユニット 予想タイプ=配列[_ $ 1] =>ユニット コンテキスト= var temp5:Array [_ $ 1] => Unit = temp3.function() for((command:FunctionCommand [_]、parameter)< - コマンドzip parametersForEachFunction){ ' –

3

parametersForEachFucntionのパラメータが正しいタイプであることを証明することはできませんが、FunctionCommand#functionには正しくパラメータ化された配列が必要です。実行時にタイプ消去のためにこれを行うことはできません。

パラメータ化を放棄し、次の作品、(これはあなたの他の質問に前に持っていただけで何効果的ではあるが):

case class FunctionCommand(function: Function1[Array[_], Unit]) 

class MyClass(commands: List[FunctionCommand]) { 
    def foo(parametersForEachFunction: Seq[Array[_]]) { 
    assert(commands.size == parametersForEachFunction.size) 
    for ((command, parameter) <- commands zip parametersForEachFunction) { 
     command.function(parameter) 
    } 
    } 
} 

val fc = FunctionCommand(xs => xs foreach println) 
val mc = new MyClass(List(fc)) 

scala> mc.foo(List(Array(1,2,3))) 
1 
2 
3 
+0

'FunctionCommand'に型パラメータがないとき、これがなぜ機能するのですか? –

+0

異なる型パラメータを持つ要素の 'List'が必要なので解決策は私には受け入れられませんが、' val mc = new MyClass(List(FunctionCommand {(_:配列[String])foreach println}、FunctionCommand { _:Array [Int])foreach println})) 'はコンパイルされません。 –

関連する問題