Scala standard library implementation for Scala.js, providing core library functionality for Scala code compiled to JavaScript
—
Essential Scala language constructs and basic functionality adapted for JavaScript execution, providing the foundation for Scala.js applications.
Provides a simplified way to create executable programs without writing an explicit main method, automatically handling program initialization and command-line arguments.
/**
* Trait that provides a main method and automatic initialization for simple programs
* Uses DelayedInit to ensure proper initialization order in JavaScript environment
*/
trait App extends DelayedInit {
/** Command-line arguments passed to the program */
val args: Array[String]
/** Timestamp when program execution started (milliseconds since Unix epoch) */
val executionStart: Long
/** Called by DelayedInit mechanism for proper initialization */
def delayedInit(x: => Unit): Unit
}Usage Examples:
// Simple executable program
object HelloWorld extends App {
println("Hello, World!")
println(s"Started at: $executionStart")
if (args.nonEmpty) {
println(s"Arguments: ${args.mkString(", ")}")
}
}
// Program with argument processing
object Calculator extends App {
if (args.length >= 3) {
val a = args(0).toDouble
val op = args(1)
val b = args(2).toDouble
val result = op match {
case "+" => a + b
case "-" => a - b
case "*" => a * b
case "/" => a / b
case _ => throw new IllegalArgumentException(s"Unknown operator: $op")
}
println(s"$a $op $b = $result")
} else {
println("Usage: Calculator <num1> <op> <num2>")
}
}Comprehensive array creation and manipulation utilities providing all standard Scala array operations optimized for JavaScript.
/**
* Factory methods and utilities for creating and manipulating arrays
*/
object Array {
/** Create array from variable number of arguments */
def apply[T](xs: T*): Array[T]
/** Create 1D array with specified dimensions */
def ofDim[T: ClassTag](n1: Int): Array[T]
/** Create 2D array with specified dimensions */
def ofDim[T: ClassTag](n1: Int, n2: Int): Array[Array[T]]
/** Create 3D array with specified dimensions */
def ofDim[T: ClassTag](n1: Int, n2: Int, n3: Int): Array[Array[Array[T]]]
/** Create 4D array with specified dimensions */
def ofDim[T: ClassTag](n1: Int, n2: Int, n3: Int, n4: Int): Array[Array[Array[Array[T]]]]
/** Create 5D array with specified dimensions */
def ofDim[T: ClassTag](n1: Int, n2: Int, n3: Int, n4: Int, n5: Int): Array[Array[Array[Array[Array[T]]]]]
/** Create empty array of specified type */
def empty[T: ClassTag]: Array[T]
/** Create array filled with specified element (call-by-name for lazy evaluation) */
def fill[T: ClassTag](n: Int)(elem: => T): Array[T]
/** Create 2D array filled with specified element */
def fill[T: ClassTag](n1: Int, n2: Int)(elem: => T): Array[Array[T]]
/** Create array by applying function to indices */
def tabulate[T: ClassTag](n: Int)(f: Int => T): Array[T]
/** Create 2D array by applying function to indices */
def tabulate[T: ClassTag](n1: Int, n2: Int)(f: (Int, Int) => T): Array[Array[T]]
/** Create array of integers in specified range (exclusive end) */
def range(start: Int, end: Int): Array[Int]
/** Create array of integers in specified range with step */
def range(start: Int, end: Int, step: Int): Array[Int]
/** Concatenate multiple arrays into single array */
def concat[T: ClassTag](xss: Array[T]*): Array[T]
/** Create array by iterating function from start value */
def iterate[T: ClassTag](start: T, len: Int)(f: T => T): Array[T]
/** Copy elements between arrays */
def copy(src: AnyRef, srcPos: Int, dest: AnyRef, destPos: Int, length: Int): Unit
/** Create new array builder for efficient array construction */
def newBuilder[T: ClassTag]: ArrayBuilder[T]
}Pre-defined Empty Arrays:
object Array {
/** Pre-allocated empty arrays for primitive types (performance optimization) */
val emptyBooleanArray: Array[Boolean]
val emptyByteArray: Array[Byte]
val emptyCharArray: Array[Char]
val emptyDoubleArray: Array[Double]
val emptyFloatArray: Array[Float]
val emptyIntArray: Array[Int]
val emptyLongArray: Array[Long]
val emptyShortArray: Array[Short]
val emptyObjectArray: Array[Object]
}Usage Examples for Empty Arrays:
import scala.Array
// Use pre-allocated empty arrays for better performance
val emptyInts = Array.emptyIntArray // Better than Array[Int]()
val emptyStrings = Array.emptyObjectArray.asInstanceOf[Array[String]]
// Efficient initialization in data structures
class IntBuffer {
private var data: Array[Int] = Array.emptyIntArray
def add(value: Int): Unit = {
if (data.length == 0) {
data = Array(value) // Allocate when needed
}
// ... rest of implementation
}
}
// Return empty arrays from functions without allocation
def filterPositive(numbers: Array[Int]): Array[Int] = {
val positive = numbers.filter(_ > 0)
if (positive.isEmpty) Array.emptyIntArray else positive
}
// Type-specific empty arrays avoid boxing overhead
def processDoubles(input: Option[Array[Double]]): Array[Double] = {
input.getOrElse(Array.emptyDoubleArray) // No boxing of primitive doubles
}Basic Array Creation:
import scala.Array
// Basic array creation
val fruits = Array("apple", "banana", "cherry")
val numbers = Array(1, 2, 3, 4, 5)
// Multi-dimensional arrays
val matrix = Array.ofDim[Int](3, 3)
val cube = Array.ofDim[Double](2, 2, 2)
// Filled arrays
val zeros = Array.fill(10)(0)
val randomNumbers = Array.fill(5)(scala.util.Random.nextInt(100))
// Function-generated arrays
val squares = Array.tabulate(10)(i => i * i)
val multiplication = Array.tabulate(5, 5)((i, j) => i * j)
// Range arrays
val oneToTen = Array.range(1, 11)
val evens = Array.range(0, 20, 2)
// Array concatenation
val combined = Array.concat(
Array(1, 2, 3),
Array(4, 5, 6),
Array(7, 8, 9)
)
// Array iteration
val powers = Array.iterate(2, 8)(_ * 2) // Powers of 2: [2, 4, 8, 16, ...]
// Array copying
val source = Array(1, 2, 3, 4, 5)
val dest = Array.ofDim[Int](10)
Array.copy(source, 0, dest, 2, source.length) // Copy to middle of destInterned string representation providing memory-efficient string constants and pattern matching support.
/**
* Immutable interned strings for efficient symbol representation
* Symbols with the same name share the same instance (flyweight pattern)
*/
case class Symbol private (name: String) {
/** String representation with leading apostrophe */
override def toString: String = s"'$name"
}
object Symbol {
/** Create or retrieve interned symbol for given name */
def apply(name: String): Symbol
}Usage Examples:
// Symbol creation
val greeting = Symbol("hello")
val status = Symbol("ok")
val error = Symbol("error")
// Symbol comparison (reference equality due to interning)
val sym1 = Symbol("test")
val sym2 = Symbol("test")
assert(sym1 eq sym2) // Same object reference
// Pattern matching with symbols
def processStatus(status: Symbol): String = status match {
case Symbol("ok") => "Success"
case Symbol("error") => "Failed"
case Symbol("pending") => "In Progress"
case _ => "Unknown"
}
// Using symbols as keys (efficient due to interning)
val statusMap = Map(
Symbol("active") -> "Running",
Symbol("inactive") -> "Stopped",
Symbol("maintenance") -> "Under Maintenance"
)Support for creating enumerated types with named constants and iteration capabilities.
/**
* Base class for creating enumerated types with named values
* Provides automatic ID assignment and iteration support
*/
abstract class Enumeration {
/** Base type for enumeration values */
type Value = EnumerationValue
/** Create enumeration value with auto-assigned ID */
protected final def Value: Value
/** Create enumeration value with specific ID */
protected final def Value(i: Int): Value
/** Create enumeration value with name and auto-assigned ID */
protected final def Value(name: String): Value
/** Create enumeration value with specific ID and name */
protected final def Value(i: Int, name: String): Value
/** Set of all values in this enumeration */
def values: ValueSet
/** Apply method to get value by ID */
def apply(x: Int): Value
/** Iterator over all values */
def iterator: Iterator[Value]
/** String representation of enumeration */
override def toString: String
}Usage Examples:
// Basic enumeration
object Color extends Enumeration {
val Red, Green, Blue = Value
}
// Named enumeration values
object Status extends Enumeration {
val Pending = Value("pending")
val Processing = Value("processing")
val Complete = Value("complete")
val Failed = Value("failed")
}
// Enumeration with custom IDs
object Priority extends Enumeration {
val Low = Value(1, "low")
val Medium = Value(5, "medium")
val High = Value(10, "high")
val Critical = Value(20, "critical")
}
// Using enumerations
val currentColor = Color.Red
val taskStatus = Status.Processing
// Pattern matching
def getColorHex(color: Color.Value): String = color match {
case Color.Red => "#FF0000"
case Color.Green => "#00FF00"
case Color.Blue => "#0000FF"
}
// Iteration over enum values
println("Available colors:")
for (color <- Color.values) {
println(s"${color.id}: ${color}")
}
// Lookup by ID
val priorityById = Priority(10) // Returns Priority.HighCore package-level functions and type aliases that provide foundational functionality.
/**
* Package-level utility functions and type aliases
* Available in scala package object
*/
// Type aliases for common types (Scala 2.13 specific)
type LazyList[+A] = scala.collection.immutable.LazyList[A]
type ::[A] = scala.collection.immutable.::[A]
// Utility functions for common operations
def identity[A](x: A): A = x
def implicitly[T](implicit e: T): T = e
def locally[T](x: T): T = x
// Assertion functions
def assert(assertion: Boolean): Unit
def assert(assertion: Boolean, message: => Any): Unit
def assume(assumption: Boolean): Unit
def assume(assumption: Boolean, message: => Any): Unit
// Require functions for preconditions
def require(requirement: Boolean): Unit
def require(requirement: Boolean, message: => Any): UnitUsage Examples:
// Identity function
val x = identity(42) // x == 42
val list = List(1, 2, 3).map(identity) // Returns same list
// Implicit parameter access
def printType[T](value: T)(implicit manifest: Manifest[T]): Unit = {
val m = implicitly[Manifest[T]]
println(s"$value has type ${m.runtimeClass.getSimpleName}")
}
// Local block evaluation
val result = locally {
val a = 10
val b = 20
a + b
} // result == 30
// Assertions and requirements
def divide(a: Double, b: Double): Double = {
require(b != 0, "Division by zero")
assert(a.isFinite && b.isFinite, "Arguments must be finite")
a / b
}
// Assumption checking (for optimization)
def optimizedSort(arr: Array[Int]): Array[Int] = {
assume(arr.length < 1000, "Algorithm optimized for small arrays")
arr.sorted
}Console I/O operations adapted for JavaScript environment, providing standard output and input capabilities.
/**
* Console I/O operations for JavaScript environment
* Provides standard input/output operations using JavaScript console and DOM APIs
*/
object Console {
/** Print object to console without newline */
def print(obj: Any): Unit
/** Print object to console with newline */
def println(obj: Any): Unit = println(obj.toString)
def println(): Unit
/** Print formatted string to console */
def printf(text: String, args: Any*): Unit
/** Read line from standard input (JavaScript prompt or Node.js stdin) */
def readLine(): String
def readLine(text: String): String
/** Error output operations */
def err: java.io.PrintStream
/** Input operations */
def in: java.io.BufferedReader
/** Output operations */
def out: java.io.PrintStream
}Usage Examples:
import scala.Console
// Basic output
Console.println("Hello, Scala.js!")
Console.print("No newline: ")
Console.println("With newline")
// Formatted output
Console.printf("Number: %d, String: %s%n", 42, "test")
// Interactive input (browser environment)
val name = Console.readLine("Enter your name: ")
Console.println(s"Hello, $name!")
// Using implicit operations
println("Direct println call") // Uses Console.println implicitly
// Error output
Console.err.println("This goes to error stream")Install with Tessl CLI
npx tessl i tessl/maven-org-scala-js--scalajs-scalalib-2-13