Expresiones frente a sentencias
Todo es una expresión
Expresiones frente a sentencias es una lección gratuita de Scala for Backend Engineering & Functional Programming en CoddyKit. Esta es la lección 3 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Scala for Backend Engineering & Functional Programming, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Scala for Backend Engineering & Functional Programming incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Expressions vs Statements
A statement does something but returns nothing useful. An expression evaluates to a value.
In Scala, almost everything is an expression. This is a core idea that shapes how you write code.
if Is an Expression
In many languages if is a statement. In Scala, if/else returns a value, so you can assign it directly to a val.
No need for a separate variable assigned in each branch.
object Main {
def main(args: Array[String]): Unit = {
val temp = 30
val label = if (temp > 25) "hot" else "mild"
println(label)
}
}Blocks Are Expressions
A block { ... } is an expression too. Its value is the value of its last line.
So you can compute intermediate values, then end with the result.
object Main {
def main(args: Array[String]): Unit = {
val result = {
val a = 2
val b = 3
a * b
}
println(result)
}
}match Is an Expression
Pattern matching with match also returns a value. Each branch produces a result, and the whole expression yields the matched branch's value.
object Main {
def main(args: Array[String]): Unit = {
val day = 3
val name = day match {
case 1 => "Mon"
case 2 => "Tue"
case 3 => "Wed"
case _ => "Other"
}
println(name)
}
}The Unit Type
Some expressions exist only for their side effect, like println. They return Unit, written ().
Unit is similar to void in other languages but is still a real value.
object Main {
def main(args: Array[String]): Unit = {
val nothing: Unit = println("side effect")
println(nothing)
}
}Returning From Functions
Because the body of a function is an expression, the last expression is its return value. You rarely need the return keyword.
Here the function body is a single expression.
object Main {
def max(a: Int, b: Int): Int = if (a > b) a else b
def main(args: Array[String]): Unit = {
println(max(7, 4))
}
}Expression-Oriented Functions
A function can be a block expression whose last line is the result. This keeps logic compact and avoids mutable temporaries.
object Main {
def discount(price: Double): Double = {
val rate = if (price > 100) 0.2 else 0.1
price * (1 - rate)
}
def main(args: Array[String]): Unit = {
println(discount(150.0))
}
}No Need for Mutation
Because if and match are expressions, you can assign their result to a val instead of mutating a var.
This leads to cleaner, more functional code.
object Main {
def main(args: Array[String]): Unit = {
val score = 85
val grade = if (score >= 90) "A"
else if (score >= 80) "B"
else "C"
println(grade)
}
}Composing Expressions
Because everything returns a value, expressions nest and compose freely. The output of one becomes the input of another.
This composability is a big reason Scala feels expressive.
object Main {
def main(args: Array[String]): Unit = {
val n = 7
val message = "n is " + (if (n % 2 == 0) "even" else "odd")
println(message)
}
}Why It Matters
Expression-oriented code:
- Reduces the need for mutable variables
- Makes the flow of values explicit
- Composes naturally into larger programs
- Pairs perfectly with immutability
All Together
Here a block expression contains an if expression, all assigned to a single immutable result.
object Main {
def main(args: Array[String]): Unit = {
val total = {
val items = 3
val each = 12
val raw = items * each
if (raw > 30) raw - 5 else raw
}
println(total)
}
}Quick Check
Check your grasp of expressions.
Recap
You learned that in Scala nearly everything is an expression:
if/else,match, and blocks all return values- A block's value is its last expression
- Side-effecting expressions return
Unit(()) - The last expression of a function is its return value
- This reduces mutation and improves composability
Preguntas frecuentes
¿La lección «Expresiones frente a sentencias» es gratis?
Sí — el texto completo de «Expresiones frente a sentencias» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Scala for Backend Engineering & Functional Programming, actualiza a CoddyKit PRO. El curso de Scala for Backend Engineering & Functional Programming incluye 4 lecciones en total.
¿Qué aprenderé en «Expresiones frente a sentencias»?
Todo es una expresión Practicas Scala for Backend Engineering & Functional Programming con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Scala for Backend Engineering & Functional Programming?
No se requiere experiencia previa. Scala for Backend Engineering & Functional Programming en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 4.
¿Cuánto tiempo toma la lección «Expresiones frente a sentencias»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Scala for Backend Engineering & Functional Programming?
Sí. Cada lección de Scala for Backend Engineering & Functional Programming incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Uso del REPL
- val, var y tipos
- Expresiones frente a sentencias
- Interpolación de strings