Scala 中的所有语法糖实例是什么? [英] What are all the instances of syntactic sugar in 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 toa.b
.a b c
is equivalent toa.b(c)
, except whenb
ends in:
. In that case,a b c
is equivalent toc.b(a)
.a(b)
is equivalent toa.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
必须具有square1
code>Function1 trait(或Function2
等...)When calling
square1(y)
, you are actually callingsquare1.apply(y)
whichsquare1
must have as specified by theFunction1
trait (orFunction2
, etc...)a(b) = c
等价于a.update(b,c)
.同样,a(b,c) = d
等价于a.update(b,c,d)
等等.a(b) = c
is equivalent toa.update(b,c)
. Likewise,a(b,c) = d
is equivalent toa.update(b,c,d)
and so on.a.b = c
等价于a.b_=(c)
.当您在类/对象中创建val
/var
x
时,Scala 创建方法x
和x_=
给你.你可以自己定义这些,但是如果你定义了y_=
你必须定义y
否则它不会编译,例如:a.b = c
is equivalent toa.b_=(c)
. When you create aval
/var
x
in a Class/Object, Scala creates the methodsx
andx_=
for you. You can define these yourself, but if you definey_=
you must definey
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 toa.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 toa = a <operator> b
only ifa
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屋!