println() (Built-in)
Scala's standard output function. Suitable for rapid log output in learning stages and quick debugging as simplest debugging means. Immediately available without configuration, but has feature limitations in full-scale application development.
Library
println() (Built-in)
Overview
Scala's standard output function provides the simplest debugging method available to developers. Suitable for rapid log output in learning stages, REPL experimental code verification, and quick debugging, it's immediately available without configuration. However, for serious Scala application development, it has functional limitations, and its use in production code is recognized as a quality issue, making migration to structured logging libraries strongly recommended.
Details
The println() function is a fundamental output capability included in Scala's standard library, responsible for console output on the JVM platform. Implemented as part of the Scala Console object, it features automatic newline character appending. Widely used for interactive programming in REPL environments and debugging during learning stages, it's fully integrated with Scala's type system. In development environments like IntelliJ IDEA, it displays as standard output, requiring special consideration when combined with ScalaTest.
Key Features
- No Configuration Required: Immediately available in Scala projects
- Automatic Newline: Automatically appends newline character after output
- Type Safe: Fully integrated with Scala's type system
- REPL Compatible: Immediate result verification in interactive environments
- JVM Integration: Interoperability with Java environments
- Simple API: Minimal learning curve required
Pros and Cons
Pros
- Available immediately in Scala projects without additional setup
- Optimal for interactive debugging and code verification in REPL environments
- Minimal learning curve, making it beginner-friendly for Scala newcomers
- Complete compatibility with Java/JVM ecosystem
- Type safety guaranteed with low risk of runtime errors
- Simple API suitable for quick debugging
Cons
- Lacks log levels and filtering capabilities
- Performance impact in production environments not considered
- No advanced features like structured logging or JSON output
- Unsuitable for log management in large-scale Scala applications
- Remnants in production code recognized as quality issues
- No log persistence or external system integration possible
Reference Pages
Code Examples
Basic Console Output
// Basic string output
println("Hello, Scala!")
// Output: Hello, Scala!
// Variable output
val name = "John Doe"
val age = 30
println(s"Name: $name, Age: $age")
// Output: Name: John Doe, Age: 30
// Numeric calculation result output
val result = 10 + 20
println(s"Calculation result: $result")
// Output: Calculation result: 30
Data Types and Collections Output
// Different data type outputs
val intValue = 42
val doubleValue = 3.14159
val boolValue = true
val charValue = 'A'
println(s"Integer: $intValue")
println(s"Double: $doubleValue")
println(s"Boolean: $boolValue")
println(s"Character: $charValue")
// Output: Integer: 42
// Output: Double: 3.14159
// Output: Boolean: true
// Output: Character: A
// Collection outputs
val numbers = List(1, 2, 3, 4, 5)
val fruits = Array("apple", "banana", "orange")
val keyValuePairs = Map("key1" -> "value1", "key2" -> "value2")
println(s"List: $numbers")
println(s"Array: ${fruits.mkString("[", ", ", "]")}")
println(s"Map: $keyValuePairs")
// Output: List: List(1, 2, 3, 4, 5)
// Output: Array: [apple, banana, orange]
// Output: Map: Map(key1 -> value1, key2 -> value2)
Function and Class Debug Output
// Debug output within functions
def calculateSum(a: Int, b: Int): Int = {
println(s"calculateSum called: a=$a, b=$b")
val result = a + b
println(s"Calculation result: $result")
result
}
val sum = calculateSum(15, 25)
// Output: calculateSum called: a=15, b=25
// Output: Calculation result: 40
// Class instance output
case class Person(name: String, age: Int, city: String)
val person = Person("Jane Smith", 28, "Chicago")
println(s"Person info: $person")
// Output: Person info: Person(Jane Smith,28,Chicago)
// Pattern matching debugging
def processValue(value: Any): Unit = {
value match {
case str: String =>
println(s"String value: $str")
case num: Int =>
println(s"Integer value: $num")
case list: List[_] =>
println(s"List value: $list")
case _ =>
println(s"Unknown type: $value")
}
}
processValue("test")
processValue(42)
processValue(List(1, 2, 3))
// Output: String value: test
// Output: Integer value: 42
// Output: List value: List(1, 2, 3)
Advanced String Formatting
// String interpolation and formatting
val temperature = 23.5
val humidity = 65.2
println(f"Weather info - Temperature: $temperature%.1f°C, Humidity: $humidity%.1f%%")
// Output: Weather info - Temperature: 23.5°C, Humidity: 65.2%
// Multi-line output
val multiLineMessage =
"""System Information:
| OS: Linux
| Memory: 8GB
| CPU: Intel Core i7""".stripMargin
println(multiLineMessage)
// Output: System Information:
// Output: OS: Linux
// Output: Memory: 8GB
// Output: CPU: Intel Core i7
// Conditional output
val debug = true
if (debug) {
println("Debug mode is enabled")
println(s"Current time: ${java.time.LocalDateTime.now()}")
}
Error Handling and Logging
import scala.util.{Try, Success, Failure}
// Try-Success-Failure pattern with log output
def divideNumbers(a: Int, b: Int): Try[Double] = {
println(s"Division process started: $a ÷ $b")
Try {
if (b == 0) throw new ArithmeticException("Division by zero error")
a.toDouble / b.toDouble
}
}
divideNumbers(10, 2) match {
case Success(result) =>
println(s"Division successful: result = $result")
case Failure(exception) =>
println(s"Division failed: ${exception.getMessage}")
}
// Output: Division process started: 10 ÷ 2
// Output: Division successful: result = 5.0
divideNumbers(10, 0) match {
case Success(result) =>
println(s"Division successful: result = $result")
case Failure(exception) =>
println(s"Division failed: ${exception.getMessage}")
}
// Output: Division process started: 10 ÷ 0
// Output: Division failed: Division by zero error
REPL and Test Environment Usage
// Interactive debugging in REPL environment
val data = (1 to 10).toList
println(s"Data generated: $data")
val filtered = data.filter(_ % 2 == 0)
println(s"Even numbers filtered: $filtered")
val mapped = filtered.map(_ * 2)
println(s"Doubled values: $mapped")
val reduced = mapped.sum
println(s"Total sum: $reduced")
// Output: Data generated: List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// Output: Even numbers filtered: List(2, 4, 6, 8, 10)
// Output: Doubled values: List(4, 8, 12, 16, 20)
// Output: Total sum: 60
// Process flow visualization
println("=== Scala Application Start ===")
println("📁 Loading configuration file...")
Thread.sleep(100) // Simulation
println("✅ Configuration file loaded")
println("🔗 Connecting to database...")
Thread.sleep(200) // Simulation
println("✅ Database connection established")
println("=== Initialization Complete ===")