簡體   English   中英

Scala中所有函數的超類型是什么?

[英]What is the supertype of all functions in Scala?

我知道我可以對Function1Function2等進行instanceOf檢查,但是有一種通用的方法來查看某些東西是否有效(它可以具有仲裁數量的args)。 我試着定義這樣的東西:

type FuncType = (Any*) -> Any

但這也不起作用。 基本上我有一些看起來像這樣的代碼:

call = (name: Any, args: Any*) -> if name.isFunction then name.castAs[Function].apply(args) else name
aFunction = (name: String) => "Hello " + name
notAFunction = "Hello rick"
call(aFunction, "rick")
call(notAFunction)

所有函數類型都沒有通用的超類型。

Scala無法對函數的arity進行抽象。 但是,您可以查看Shapeless庫,它引入了一個名為HList東西,您可以使用它來抽象函數的arity。

但是,我認為這不是你真正需要的。 聽起來你只是想做一個像“這是一個功能嗎?”的檢查。 你可能會覺得奇怪的是,沒有與arity無關的Function超類型,但如果你想對它做一些有用的事情,你幾乎總是需要知道一個函數的arity。

或者,您可以使用函數的curried方法執行某些操作,該函數將返回Function1

不,沒有辦法做到這一點,除了通過並檢查每個Function1Function2等。每個特征的AnyRefAnyRef ,它不會幫助你區別於其他任何東西。 每個traits的apply方法都使用不同數量的參數,因此無法為它們提供具有apply方法的父級。 你可能接近你想要做的最接近的是:

def arbitraryFunction(function: AnyRef, args: Seq[Any]): Any = {
  function match {
    case f: Function1[Any, Any] => f(args(0))
    case f: Function2[Any, Any, Any] => f(args(0), args(1))
    // and so on
  }
}

但這是瘋狂和危險的,如果類型錯誤,將在運行時拋出異常,例如

arbitraryFunction((x: Int) => x * 2, List("I'm a String!"))

暫無
暫無

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

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