什么时候可以省略括号、点、大括号、=(函数)等的精确规则是什么? [英] What are the precise rules for when you can omit parenthesis, dots, braces, = (functions), etc.?

查看:59
本文介绍了什么时候可以省略括号、点、大括号、=(函数)等的精确规则是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候可以省略(省略)括号、点、大括号、=(函数)等的确切规则是什么?

What are the precise rules for when you can omit (omit) parentheses, dots, braces, = (functions), etc.?

例如,

(service.findAllPresentations.get.first.votes.size) must be equalTo(2).

  • service 是我的对象
  • def findAllPresentations: Option[List[Presentation]]
  • votes 返回 List[Vote]
  • mustbe 都是规范的功能
    • service is my object
    • def findAllPresentations: Option[List[Presentation]]
    • votes returns List[Vote]
    • must and be are both functions of specs
    • 为什么我不能去:

      (service findAllPresentations get first votes size) must be equalTo(2)
      

      ?

      编译错误是:

      "RestServicesSpecTest.this.service.findAllPresentations类型选项[列表[com.sharca.Presentation]]不带参数"

      "RestServicesSpecTest.this.service.findAllPresentations of type Option[List[com.sharca.Presentation]] does not take parameters"

      为什么它认为我试图传入一个参数?为什么每次方法调用都必须使用点?

      Why does it think I'm trying to pass in a parameter? Why must I use dots for every method call?

      为什么必须 (service.findAllPresentations get first votes size) is equalTo(2) 结果:

      Why must (service.findAllPresentations get first votes size) be equalTo(2) result in:

      未找到:值优先"

      然而,必须等于 2"(service.findAllPresentations.get.first.votes.size) 必须是equalTo 2,也就是方法链正常吗?- 对象链链链参数.

      Yet, the "must be equalTo 2" of (service.findAllPresentations.get.first.votes.size) must be equalTo 2, that is, method chaining works fine? - object chain chain chain param.

      我浏览了 Scala 书籍和网站,但找不到全面的解释.

      I've looked through the Scala book and website and can't really find a comprehensive explanation.

      事实上,正如 Rob H 在 Stack Overflow 问题中解释的那样Which我可以在 Scala 中省略字符吗?,这是省略 '.' 的唯一有效用例是用于操作数运算符操作数"样式的操作,而不是用于方法链?

      Is it in fact, as Rob H explains in Stack Overflow question Which characters can I omit in Scala?, that the only valid use-case for omitting the '.' is for "operand operator operand" style operations, and not for method chaining?

      推荐答案

      类定义:

      valvar 可以从类参数中省略,这将使参数成为私有.

      Class definitions:

      val or var can be omitted from class parameters which will make the parameter private.

      添加 var 或 val 会使其成为 public(即生成方法访问器和修改器).

      Adding var or val will cause it to be public (that is, method accessors and mutators are generated).

      {} 如果类没有主体可以省略,即

      {} can be omitted if the class has no body, that is,

      class EmptyClass
      

      <小时>

      类实例化:

      如果编译器可以推断出通用参数,则可以省略它们.但是请注意,如果您的类型不匹配,则始终推断类型参数以使其匹配.所以不指定类型,你可能得不到你所期望的——也就是说,给定


      Class instantiation:

      Generic parameters can be omitted if they can be inferred by the compiler. However note, if your types don't match, then the type parameter is always infered so that it matches. So without specifying the type, you may not get what you expect - that is, given

      class D[T](val x:T, val y:T);
      

      这会给你一个类型错误(Int found, expected String)

      var zz = new D[String]("Hi1", 1) // type error
      

      虽然这工作正常:

      var z = new D("Hi1", 1)
      == D{def x: Any; def y: Any}
      

      因为类型参数 T 被推断为两者中最不常见的超类型 - Any.

      Because the type parameter, T, is inferred as the least common supertype of the two - Any.

      = 如果函数返回 Unit (nothing),则可以删除.

      = can be dropped if the function returns Unit (nothing).

      {},但前提是该语句返回一个值(您需要 = 符号),也就是说,

      {} for the function body can be dropped if the function is a single statement, but only if the statement returns a value (you need the = sign), that is,

      def returnAString = "Hi!"
      

      但这不起作用:

      def returnAString "Hi!" // Compile error - '=' expected but string literal found."
      

      如果可以推断出函数的返回类型,则可以省略它(递归方法必须指定其返回类型).

      The return type of the function can be omitted if it can be inferred (a recursive method must have its return type specified).

      () 如果函数不带任何参数,则可以删除,即

      () can be dropped if the function doesn't take any arguments, that is,

      def endOfString {
        return "myDog".substring(2,1)
      }
      

      按照惯例,它是为没有副作用的方法保留的 - 稍后会详细介绍.

      which by convention is reserved for methods which have no side effects - more on that later.

      () 本身实际上并未删除c-programmers-part-3-pass-by-name.html" rel="noreferrer">按名称传递 参数,但实际上是语义上完全不同的表示法,即>

      () isn't actually dropped per se when defining a pass by name paramenter, but it is actually a quite semantically different notation, that is,

      def myOp(passByNameString: => String)
      

      说 myOp 接受一个按名称传递的参数,结果是一个字符串(即它可以是一个返回字符串的代码块),而不是函数参数,

      Says myOp takes a pass-by-name parameter, which results in a String (that is, it can be a code block which returns a string) as opposed to function parameters,

      def myOp(functionParam: () => String)
      

      表示 myOp 接受一个参数为零的函数并返回一个字符串.

      which says myOp takes a function which has zero parameters and returns a String.

      (请注意,按名称传递的参数会被编译成函数;它只会使语法更好.)

      (Mind you, pass-by-name parameters get compiled into functions; it just makes the syntax nicer.)

      () 如果函数只带一个参数,可以在函数参数定义中去掉,例如:

      () can be dropped in the function parameter definition if the function only takes one argument, for example:

      def myOp2(passByNameString:(Int) => String) { .. } // - You can drop the ()
      def myOp2(passByNameString:Int => String) { .. }
      

      但如果需要多个参数,则必须包含 ():

      But if it takes more than one argument, you must include the ():

      def myOp2(passByNameString:(Int, String) => String) { .. }
      

      <小时>

      声明:

      . 可以删除以使用运算符表示法,它只能用于中缀运算符(带参数的方法的运算符).请参阅 丹尼尔的回答了解更多信息.


      Statements:

      . can be dropped to use operator notation, which can only be used for infix operators (operators of methods that take arguments). See Daniel's answer for more information.

      • . 也可以删除后缀函数列表尾部

      • . can also be dropped for postfix functions list tail

      () 可以删除后缀运算符list.tail

      () can be dropped for postfix operators list.tail

      () 不能与定义如下的方法一起使用:

      () cannot be used with methods defined as:

      def aMethod = "hi!" // Missing () on method definition
      aMethod // Works
      aMethod() // Compile error when calling method
      

      因为这个表示法是为没有副作用的方法保留的约定,比如List#tail(也就是说,调用一个没有副作用的函数意味着该函数没有可观察的效果,除了它的返回值).

      Because this notation is reserved by convention for methods that have no side effects, like List#tail (that is, the invocation of a function with no side effects means that the function has no observable effect, except for its return value).

      • () 可以在传入单个参数时删除运算符符号

      • () can be dropped for operator notation when passing in a single argument

      () 可能需要使用不在语句末尾的后缀运算符

      () may be required to use postfix operators which aren't at the end of a statement

      () 可能需要指定嵌套语句、匿名函数的结尾或带有多个参数的运算符

      () may be required to designate nested statements, ends of anonymous functions or for operators which take more than one parameter

      当调用一个带函数的函数时,内部函数定义中不能省略(),例如:

      When calling a function which takes a function, you cannot omit the () from the inner function definition, for example:

      def myOp3(paramFunc0:() => String) {
          println(paramFunc0)
      }
      myOp3(() => "myop3") // Works
      myOp3(=> "myop3") // Doesn't work
      

      调用带有按名称参数的函数时,您不能将参数指定为无参数匿名函数.例如,给定:

      When calling a function that takes a by-name parameter, you cannot specify the argument as a parameter-less anonymous function. For example, given:

      def myOp2(passByNameString:Int => String) {
        println(passByNameString)
      }
      

      您必须将其称为:

      myOp("myop3")
      

      myOp({
        val source = sourceProvider.source
        val p = myObject.findNameFromSource(source)
        p
      })
      

      但不是:

      myOp(() => "myop3") // Doesn't work
      

      IMO,过度使用删除返回类型可能对代码的重用有害.只需查看规范中的一个很好的示例,该示例就会因代码中缺乏明确信息而降低可读性.实际找出变量类型的间接级别的数量可能很疯狂.希望更好的工具可以避免这个问题并保持我们的代码简洁.

      IMO, overuse of dropping return types can be harmful for code to be re-used. Just look at specification for a good example of reduced readability due to lack of explicit information in the code. The number of levels of indirection to actually figure out what the type of a variable is can be nuts. Hopefully better tools can avert this problem and keep our code concise.

      (好吧,为了编译一个更完整、更简洁的答案(如果我遗漏了什么,或者得到了什么错误/不准确的请评论),我已经添加到答案的开头.请注意这不是语言规范,所以我不想让它在学术上完全正确 - 更像是一张参考卡.)

      这篇关于什么时候可以省略括号、点、大括号、=(函数)等的精确规则是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆