Scala - 传入void函数作为参数

时间:2016-01-12 09:41:48

标签: scala

我有一个带有如下定义的构造函数的类:

public static <T extends Component> T 
   createContainerAndShow(String framesetid, Component component)

和另一个名为FrameFactory的java类,其方法如下:

new Worker(
    action = "actionName",
    owner = null,
    validate = (scopeObject) => {true},
    model = (scopeObject) => {},
    connector = (scopeObject: RequestScopeObject) => {
      FrameFactory.createContainerAndShow("string", new JPanel())
      () // forced to put a '()'  here as FrameFactory.createContainerAndShow 
         //returns the Jpanel created
    }
  ))

当我创建一个Worker类的实例时,如下所示:

{{1}}

我想知道是否有更好的写作方式?如何将连接器参数声明为返回Unit并忽略FrameFactory返回的JPanel的函数

2 个答案:

答案 0 :(得分:1)

你可以简单地忽略这样一个事实:你的连接器看起来像是在返回一个帧,编译器知道它是函数$key = Get-ItemProperty HKLM:\SOFTWARE\Microsoft\VisualStudio\8.0 $dir = [string] (Get-ItemProperty $key.InstallDir) $dir += "PrivateAssemblies\" $lib = $dir + "Microsoft.TeamFoundation.WorkItemTracking.Client.dll" [Reflection.Assembly]::LoadFrom($lib) $lib = $dir + "Microsoft.TeamFoundation.Client.dll" [Reflection.Assembly]::LoadFrom($lib) "Please enter your Team Foundation Server Name:" $server = [Console]::ReadLine() $server = $server.Trim() "Connecting to " + $server + "..." $tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($server) $type = [Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore] $store = [Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore] $tfs.GetService($type) $workItem = new-object Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItem($store.Projects[0].WorkItemTypes[0]) "Created a new work item of type " + $workItem.Type.Name $workItem.Title = "Created by Windows PowerShell!" $workItem.Save() ,它将被视为这样。您可以将其视为编译器将RequestScopeObject => Unit添加为函数中的最后一个语句。

另请注意,如果您只有一条指令,则不需要大括号,并且您也不需要围绕单个参数的parens。

()

答案 1 :(得分:1)

您不必强行将()放在功能块的末尾。如果函数返回类型的类型为Unit,则不会返回最后一个块表达式的实例。

考虑以下示例:

def f(g: Int => Unit) = {}
f((x: Int) => 3)