Scala 中的所有语法糖实例是什么? [英] What are all the instances of syntactic sugar in Scala?

查看:50
本文介绍了Scala 中的所有语法糖实例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala 中的所有语法糖实例是什么?

What are all the instances of syntactic sugar in Scala?

它们很难搜索,因为它们大部分/全部都是纯粹的符号,因此在不知道概念名称的情况下很难搜索.

They are hard to search for since most/all of them are purely symbols and are thus hard to search for without knowing the name of the concept.

待办事项:

  • 隐式转换
  • _ 匿名函数的语法
  • 我忘记的其他事情

推荐答案

基础:

  • a b 等价于 a.b.
  • a b c 等价于 a.b(c),除非 b: 结尾.在这种情况下,a b c 等价于 c.b(a).
  • a(b) 等价于 a.apply(b) 这就是匿名函数的以下定义相同的原因:

    Basics:

    • a b is equivalent to a.b.
    • a b c is equivalent to a.b(c), except when b ends in :. In that case, a b c is equivalent to c.b(a).
    • a(b) is equivalent to a.apply(b) This is why the following definitions for an anonymous functions are identical:

      val square1 = (x: Int) => x*x
      val square2 = new Function1[Int,Int] {
          def apply(x: Int) = x*x
      }
      

      当调用 square1(y) 时,您实际上是在调用 square1.apply(y)square1 必须具有 square1code>Function1 trait(或 Function2 等...)

      When calling square1(y), you are actually calling square1.apply(y) which square1 must have as specified by the Function1 trait (or Function2, etc...)

      a(b) = c 等价于 a.update(b,c).同样,a(b,c) = d 等价于 a.update(b,c,d) 等等.

      a(b) = c is equivalent to a.update(b,c). Likewise, a(b,c) = d is equivalent to a.update(b,c,d) and so on.

      a.b = c 等价于 a.b_=(c).当您在类/对象中创建 val/var x 时,Scala 创建方法 xx_= 给你.你可以自己定义这些,但是如果你定义了 y_=必须定义 y 否则它不会编译,例如:

      a.b = c is equivalent to a.b_=(c). When you create a val/var x in a Class/Object, Scala creates the methods x and x_= for you. You can define these yourself, but if you define y_= you must define y or it will not compile, for example:

      scala> val b = new Object{ def set_=(a: Int) = println(a) }
      b: java.lang.Object{def set_=(Int): Unit} = $anon$1@17e4cec
      
      scala> b.set = 5
      <console>:6: error: value set is not a member of java.lang.Object{def set_=(Int): Unit}
             b.set = 5
               ^
      
      scala> val c = new Object{ def set = 0 ; def set_=(a:Int) = println(a) }
      c: java.lang.Object{def set: Int; def set_=(Int): Unit} = $anon$1@95a253
      
      scala> c.set = 5
      5
      

    • -a 对应于 a.unary_-.对于 +a~a!a 也是如此.

    • -a corresponds to a.unary_-. Likewise for +a,~a, and !a.

      a <operator>= b,其中 是一组特殊字符,等价于 a = a <运营商>b only 如果 a 没有 = 方法,例如:

      a <operator>= b, where <operator> is some set of special characters, is equivalent to a = a <operator> b only if a doesn't have the <operator>= method, for example:

      class test(val x:Int) {
          def %%(y: Int) = new test(x*y)
      }
      
      var a = new test(10)
      a.x // 10
      a %%= 5 // Equivalent to a = a %% 5
      a.x // 50
      

    • 这篇关于Scala 中的所有语法糖实例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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