在def中返回数组的第一个元素

哈特穆特·P。

您能否帮助我理解为什么第二个def未编译,以及如何为其编写第二个def(在一行中返回Array的第一个条目)。谢谢!

import java.awt.{GraphicsDevice, GraphicsEnvironment}

class SeparatedTestCase {

   def does_compile: GraphicsDevice = {
      val ge: GraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment
      val devices: Array[GraphicsDevice] = ge.getScreenDevices
      devices(0)
   }

   def does_not_compile: GraphicsDevice = {
      val ge: GraphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment
      val device0: GraphicsDevice = (ge.getScreenDevices)(0)   // <---- compile error
      device0
   }
}

//Error:(13, 59) no arguments allowed for nullary method getScreenDevices: ()Array[java.awt.GraphicsDevice]
//val device0: GraphicsDevice = (ge.getScreenDevices)(0)
弗拉基米尔·马特维耶夫(Vladimir Matveev)

您必须使用显式括号来调用该方法:

ge.getScreenDevices()(0)

这不会编译,因为第二次调用的含义与

ge.getScreenDevices(0)

它不执行您想要的操作,因为这getScreenDevices是一个Java无效二进制方法,可以用括号调用或不使用括号调用,如果指定了一组括号,Scala假定您要使用这些参数调用该方法,当然由于它不接受任何参数,因此无法使用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章