Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are all the instances of syntactic sugar in 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.

TODO:

  • Implicit conversions
  • _ syntax for anonymous functions
  • Other things I'm forgetting
like image 687
Jackson Davis Avatar asked Apr 18 '10 16:04

Jackson Davis


People also ask

What is syntactic sugar in Scala?

Scala provides some useful syntactic sugars. Syntactic Sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language “sweeter” for human use.

Is Destructuring syntactic sugar?

Destructuring is syntactic sugar for creating new variables by assigning properties from objects or items from arrays. Destructuring works for both objects and arrays.


1 Answers

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 } 

    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 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 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 corresponds to a.unary_-. Likewise for +a,~a, and !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 
like image 159
Jackson Davis Avatar answered Sep 27 '22 22:09

Jackson Davis