summaryrefslogtreecommitdiff
path: root/book/src/main/scalatex/book/indepth/SemanticDifferences.scalatex
blob: ebfd1db336b9aa84740b11efd9bbb713187790f3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
@import BookData._
@p
  Although Scala.js tries very hard to maintain compatibility with Scala-JVM, there are some parts where the two platforms differs. This can be roughly grouped into two things: differences in the libraries available,and differences in the language itself. This chapter will cover both of these facets.

@sect{Language Differences}
  @sect{Floats are Doubles}
    @p
      Since JavaScript doesn't have a native float type, we sometimes represent Floats using doubles/numbers, rather than with lower-precision 32-bit floats.
    @p
      The choice of how to represent floats is up to the implementation. You may not rely on floats providing 64-bit floating point precision.
    @p
      Float literals are truncated to their (binary) precision. However, output does not truncate to that precision. This can lead to the following behavior (this works as expected when using doubles):

  @split
    @half
      @hl.scala
        // Scala-JVM
        > println(13.345f)
        13.345

    @half
      @hl.scala
        // Scala.js
        > println(13.345f)
        13.345000267028809

  @sect{Int division by 0 is undefined}
    @p
      Unlike the JVM where dividing an integer type by 0 throws an exception, in Scala.js integer division by 0 is undefined. This allows for efficient implementation of division. Dividing a Double or Float by 0 yields positive or negative infinity as expected.

    @split
      @half
        @hl.scala
          // Scala-JVM
          > 10 / 0
          java.lang.ArithmeticException: / by zero
      @half
        @hl.scala
          // Scala.js
          > 10 / 0
          0

    @p
      This is a consequence of the eternal trade-off between performance and correctness, as described in the section @sect.ref{Why does error behavior differ?}

  @sect{Primitive isInstanceOf tests are based on value}
    @p
      Instance tests (and consequently pattern matching) on any of @hl.scala{Byte}, @hl.scala{Short}, @hl.scala{Int}, @hl.scala{Float}, @hl.scala{Double} are based on the value and not the type they were created with. The following are examples:

    @ul
      @li
        @hl.scala{1} matches @hl.scala{Byte}, @hl.scala{Short}, @hl.scala{Int}, @hl.scala{Float}, @hl.scala{Double}
      @li
        @hl.scala{128} (> @hl.scala{Byte.MaxValue}) matches @hl.scala{Short}, @hl.scala{Int}, @hl.scala{Float}, @hl.scala{Double}
      @li
        @hl.scala{32768} (> @hl.scala{Short.MaxValue}) matches @hl.scala{Int}, @hl.scala{Float}, @hl.scala{Double}
      @li
        @hl.scala{2147483648} (> @hl.scala{Int.MaxValue}) matches @hl.scala{Float}, @hl.scala{Double}
      @li
        @hl.scala{1.2} matches @hl.scala{Float}, @hl.scala{Double}
    @p
      As a consequence, the following apparent subtyping relationship holds:

    @hl.scala
      Byte <:< Short <:< Int <:< Float =:= Double

  @sect{toString for integral Floats and Doubles}
    @p
      Calling toString on a Float or a Double that holds an integral value, will not append ".0" to that value:

    @split
      @half
        @hl.scala
          // Scala-JVM:
          > println(1.0)
          1.0
      @half
        @hl.scala
          // Scala.js:
          > println(1.0)
          1
    @p
      This is due to how numeric values are represented at runtime in Scala.js: @hl.scala{Float}s and @hl.scala{Double}s are raw Javascript @hl.scala{Number}s, and their @hl.scala{toString} behavior follows from that.

    @p
      Use a formatting interpolator if you always want to show decimals:

    @hl.scala
      val x = 1.0
      println(f"$x%.1f")
      // Scala-JVM:    1.0
      // Scala.js: 1.0

  @sect{Unit}
    @p
      @hl.scala{scala.Unit} is represented using JavaScript's undefined. Therefore, calling @hl.scala{toString()} on @hl.scala{Unit} will return @hl.scala{"undefined"} rather than @hl.scala{"()"}. In practice, this shouldn't matter for most use cases.

  @sect{Reflection}
    @p
      Java reflection and Scala reflection, are not supported. There is limited support for @lnk("java.lang.Class", "https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html"), e.g., @hl.scala{obj.getClass.getName} will work for any Scala.js object but not for objects that come from JavaScript interop (i.e. anything which @hl.scala{extends js.Object}). Reflection makes it difficult to perform the optimizations that Scala.js heavily relies on. For a more detailed discussion on this topic, take a look at the section @sect.ref{Why No Reflection?}.

  @sect{Exceptions}
    @p
      In general, Scala.js supports exceptions, including catching them based on their type. However, exceptions that are typically triggered by the JVM have flaky semantics, in particular:

    @ul
      @li
        @hl.scala{ArrayIndexOutOfBoundsException} is never thrown. Instead, the value becomes @hl.javascript{undefined}, which will probably propagate through your program and blow up somewhat later.
      @li
        @hl.scala{NullPointerException} is reported as JavaScript @hl.scala{TypeError} instead.
      @li
        @hl.scala{StackOverflowError} is unsupported since the underlying JavaScript exception type varies based on the browser. e.g. in Chrome the browser just hangs and kills the process/tab without any chance for the developer to catch the error.

  @sect{Regular expressions}
    @p
      JavaScript regular expressions are slightly different from Java regular expressions. The support for regular expressions in Scala.js is implemented on top of JavaScript regexes.
    @p
      This sometimes has an impact on functions in the Scala library that use regular expressions themselves. A list of known functions that are affected is given here:
    @ul
      @li
        @hl.scala{StringLike.split(x: Array[Char])}

  @sect{Symbols}
    @p
      @hl.scala{scala.Symbol} is supported, but is a potential source of memory leaks in applications that make heavy use of symbols. The main reason is that JavaScript does not support weak references, causing all symbols created by Scala.js tow remain in memory throughout the lifetime of the application.

  @sect{Enumerations}
    @p
      The methods @hl.scala{Value()} and @hl.scala{Value(i: Int)} on @lnk.scala{scala.Enumeration} use reflection to retrieve a string representation of the member name and are therefore -- in principle -- unsupported. However, since Enumerations are an integral part of the Scala library, Scala.js adds limited support for these two methods:
    @p
      Calls to either of these two methods of the forms:
    @hl.scala
      val <ident> = Value
      val <ident> = Value(<num>)
    @p
      are statically rewritten to (a slightly more complicated version of):
    @hl.scala
      val <ident> = Value("<ident>")
      val <ident> = Value(<num>,"<ident>")
    @p
      Note that this also includes calls like
    @hl.scala
      val A,B,C,D = Value
    @p
      since they are desugared into separate val definitions.
    @p
      Calls to either of these two methods which could not be rewritten, or calls to constructors of the protected Val class without an explicit name as parameter, will issue a warning.
    @p
      Note that the name rewriting honors the @hl.scala{nextName} iterator. Therefore, the full rewrite is:
    @hl.scala
      val <ident> = Value(
        if (nextName != null && nextName.hasNext)
          nextName.next()
        else
          "<ident>"
      )
    @p
      We believe that this covers most use cases of scala.Enumeration. Please let us know if another (generalized) rewrite would make your life easier.

@sect{Library Differences}
  @val myTable = Seq(
    ("Most of java.lang.*", "java.lang.Thread, java.lang.Runtime, ..."),
    ("Almost all of scala.*", "scala.collection.parallel, scala.tools.nsc"),
    ("Some of java.util.*", "org.omg.CORBA, sun.misc.*"),
    ("Macros: uPickle, Scala-Async, Scalaxy, etc", "Reflection: Scala-Pickling, Scala-Reflect"),
    ("Shapeless, Scalaz, Scalatags, uTest", "Scalatest, Scalate"),
    ("XMLHttpRequest, Websockets. Localstorage", "Netty, Akka, Spray, File IO, JNI"),
    ("HTML DOM, Canvas, WebGL", "AWT, Swing, SWT, OpenGL"),
    ("Chipmunk.js, Hand.js, React.js, jQuery", "Guice, JUnit, Apache-Commons, log4j"),
    ("IntelliJ, Eclipse, SBT, Chrome console, Firebug", "Scala REPL, Yourkit, VisualVM, JProfiler")
  )

  @p
    Scala.js differs from Scala-JVM not just in the corner-cases of the language, but also in the libraries available. Scala-JVM has access to JVM APIs and the wealth of the Java libraries, while Scala.js has access to Javascript APIs and Javascript libraries. It's also possible to write pure-Scala libraries that run on both Scala.js and Scala-JVM, as detailed @a("here").
  @p
    This table gives a quick overview of the sorts of libraries you can and can't use when working on Scala.js:

  @val tableHead = pureTable(th("Can Use"), th("Can't Use"))

  @tableHead
    @for(tuple <- myTable)
      @tr
        @td{@tuple._1}@td{@tuple._2}

  @p
    We'll go into each section bit by bit

  @sect{Standard Library}
    @tableHead
      @for(tuple <- myTable.slice(0, 3))
        @tr
          @td{@tuple._1}@td{@tuple._2}

    @p
      You can use more-or-less the whole Scala standard library in Scala.js, sans some more esoteric components like the parallel collections or the tools. Furthermore, we've ported some subset of the Java standard library that many common Scala libraries depends on, including most of @hl.scala{java.lang.*} and some of @hl.scala{java.util.*}.
    @p
      There isn't a full list of standard library library APIs which are available from Scala.js, but it should be enough to give you a rough idea of what is supported. The full list of classes that have been ported to Scala.js is available under @sect.ref{Available Java APIs}

  @sect{Macros v.s. Reflection}
    @tableHead
      @for(tuple <- myTable.slice(3, 4))
        @tr
          @td{@tuple._1}@td{@tuple._2}

    @p
      As described @sect.ref("Why No Reflection?", "here"), Reflection is not supported in Scala.js, due to the way it inhibits optimization. This doesn't just mean you can't use reflection yourself: many third-party libraries also use reflection, and you won't be able to use them either.

    @p
      On the other hand, Scala.js does support Macros, and macros can in many ways substitute many of the use cases that people have traditionally used reflection for (see @sect.ref("Macros", "here")). For example, instead of using a reflection-based serialization library like @lnk.github.scalaPickling, you can use a macro-based library such as @lnk.github.uPickle.

  @sect{Pure-Scala v.s. Java Libraries}
    @tableHead
      @for(tuple <- myTable.slice(4, 5))
        @tr
          @td{@tuple._1}@td{@tuple._2}
    @p
      Scala.js has access to any pure-Scala libraries that you have cross-compiled to Scala.js, and cross-compiling a pure-Scala library with no dependencies is straightforward. Many of them, such as the ones listed above, have already been cross-compiled and can be used via their maven coordinates.
    @p
      You cannot use any libraries which have a Java dependency. This means libraries like @lnk.misc.ScalaTest or @lnk.misc.Scalate, which depend on a number of external Java libraries or source files, cannot be used from Scala.js. You can only use libraries which have no dependency on Java libraries or sources.

  @sect{Javascript APIs v.s. JVM APIs}
    @tableHead
      @for(tuple <- myTable.slice(5, 7))
        @tr
          @td{@tuple._1}@td{@tuple._2}

    @p
      Apart from depending on Java sources, the other thing that you can't use in Scala.js are JVM-specific APIs. This means that anything which goes down to the underlying operating system, filesystem, GUI or network are unavailable in Scala.js. This makes sense when you consider that these capabilities are no provided by the browser which Scala.js runs in, and it's impossible to re-implement them ourselves.
    @p
      In exchange for this, Scala.js provides you access to Browser APIs that do related things. Although you can't set up a HTTP server to take in-bound requests, you can make out-bound requests using @lnk.dom.XMLHttpRequest to other servers. You can't write to the filesystem or databases directly, but you can write to the @hl.scala{dom.localStorage} provided by the browser. You can't use Swing or AWT or WebGL but instead work with the DOM and Canvas and WebGL.
    @p
      Naturally, none of these are an exact replacement, as the browser environment is fundamentally different from that of a desktop application running on the JVM. Nonetheless, there are many analogues, and if so desired you can write code to abstract away these differences and run on both Scala.js and Scala-JVM


  @sect{Scala/Browser tooling v.s. Java tooling}
    @tableHead
      @for(tuple <- myTable.slice(7, 8))
        @tr
          @td{@tuple._1}@td{@tuple._2}


    @p
      Lastly, there is the matter of tools. Naturally, all the Scala tools which depend on the JVM are out. This means things like the @lnk("Yourkit", "http://www.yourkit.com/"), @lnk("VisualVM", "http://visualvm.java.net/") and @lnk("JProfiler", "https://www.ej-technologies.com/products/jprofiler/overview.html") profilers, as well as things like the Scala command-line REPL which relies on classloaders and other such things to run on the JVM
    @p
      On the other hand, you do get to keep and continue using many tools which are build for Scala but JVM-agnostic. For example, IDEs such a @lnk.misc.IntelliJ and @lnk.misc.Eclipse work great with Scala.js; from their point of view, it's just Scala, and things like code-navigation, refactoring and error-highlighting all work out of the box. SBT works with Scala.js too, and you see the same compile-erorrs in the command-line as you would in vanilla Scala, and even things like incremental compilation work un-changed.
    @p
      Lastly, you gain access to browser tools that don't work with normal Scala: you can use the Chrome or Firefox consoles to poke at your Scala.js application from the command line, or their profilers/debuggers. With source maps set up, you can even step-through debug your Scala.js application directly in Chrome.