Skip to content

js.Dynamic.literal does not generate a JS object literal with Scala 2.13/3. #5017

Open
@trival

Description

@trival

I have this Scala file object-literal.scala :

//> using scala 3.4.2
//> using jsVersion 1.16.0
//> using jsMode full
//> using jsModuleKind es
//> using dep org.scala-js:scalajs-library_2.13:1.16.0

import scala.scalajs.js.annotation.*
import scala.scalajs.js

@JSExportTopLevel("testObj1")
val testObj1 = js.Dynamic.literal(a = 1, b = 2)

@JSExportTopLevel("testObj2")
val testObj2 = new js.Object:
  val a = 1
  val b = 2

and compile it using Scala CLI version: 1.4.3:

scala-cli --power package --js -f object-literal.scala

The relevant generated js output (formatted using prettier):

function $c_Lobject$minusliteral$package$() {
	$n_Lobject$minusliteral$package$ = this;
	$t_Lobject$minusliteral$package$__testObj1 = $m_sjs_js_special_package$().ar(
		$m_sr_ScalaRunTime$().az(
			new ($d_T2.r().C)([new $c_T2("a", 1), new $c_T2("b", 2)])
		)
	);
	$t_Lobject$minusliteral$package$__testObj2 = (() => {
		var this$6 = {};
		this$6.a = 0;
		this$6.b = 0;
		this$6.a = 1;
		this$6.b = 2;
		return this$6;
	})();
}

I assume that using above scala-cli configuration, all available optimizations are applied to compiling and linking the code.
But no object literal was generated, as stated in the docs. Instead, a pretty complex expression is emitted.

Using an anonymous js.Object instance as in testObj2 comes closer to a native object definition.

Background: Seeing how easy it is to compile scala to js using scala-cli, I was hoping to develop a concise and lightweight DSL with scala.js on top of an audio processing library using a verbose js API, and to use this DSL alongside the rest of a js/ts codebase. But seeing that js.Dynamic.literal - which would be needed a lot - is emitting pretty complex code, i am worrying about too much overhead with such a solution.

Metadata

Metadata

Assignees

Labels

optimizationOptimization only. Does not affect semantics or correctness.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions