簡體   English   中英

何時必須將我的方法視為 Scala 中的部分應用函數?

[英]When do I have to treat my methods as partially applied functions in Scala?

我注意到,當我使用期望其他函數作為參數的函數時,有時我可以這樣做:

someFunction(firstParam,anotherFunction)

但其他時候,編譯器給我一個錯誤,告訴我應該像這樣寫一個 function,以便它把它當作一個部分應用的 function:

someFunction(firstParam,anotherFunction _)

例如,如果我有這個:

object Whatever {
    def meth1(params:Array[Int]) = ...
    def meth2(params:Array[Int]) = ...
}

import Whatever._
val callbacks = Array(meth1 _,meth2 _)

為什么我不能有如下代碼:

val callbacks = Array(meth1,meth2)

在什么情況下編譯器會告訴我添加_

規則實際上很簡單:只要編譯器沒有明確期望Function object,您就必須編寫_

REPL 中的示例:

scala> def f(i: Int) = i    
f: (i: Int)Int

scala> val g = f
<console>:6: error: missing arguments for method f in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       val g = f
               ^

scala> val g: Int => Int = f  
g: (Int) => Int = <function1>

在 Scala 中,方法不是function。 編譯器可以隱式轉換 function 中的方法,但需要知道是哪一種。 因此,要么您使用_顯式轉換它,要么您可以給出一些關於使用哪種 function 類型的指示:

object Whatever {
  def meth1(params:Array[Int]): Int = ...
  def meth2(params:Array[Int]): Int = ...
}

import Whatever._
val callbacks = Array[ Array[Int] => Int ]( meth1, meth2 )

或者:

val callbacks: Array[ Array[Int] => Int ] = Array( meth1, meth2 )    

除了 Jean-Philippe Pellet 所說的,您可以在編寫委托類時使用部分應用函數:

class ThirdPartyAPI{
   def f(a: Int, b: String, c: Int) = ...
   // lots of other methods
}

// You want to hide all the unnecessary methods
class APIWrapper(r: ThirdPartyAPI) {
   // instead of writing this
   def f(a: Int, b: String, c: Int) = r.f(a, b, c)
   // you can write this
   def f(a: Int, b: String, c: Int) = r.f _
   // or even this
   def f = r.f _
}

編輯添加了def f = r.f _部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM