0Pricing
Scala for Backend Engineering & Functional Programming · 강의

기본 구문과 타입

Scala의 기본 구문, 변수 선언(val/var), 일반적인 데이터 타입과 기본 연산자를 이해합니다.

기본 구문과 타입은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 3개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 3개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Scala's Clean Syntax

Welcome to Scala's basic syntax! Scala is designed to be concise and expressive, often allowing you to write less code to achieve more.

Unlike some languages, semicolons are usually optional at the end of a line if there's only one statement. This helps keep your code clean.

Expressions Are Key

In Scala, almost everything is an expression, meaning it evaluates to a value. This is a powerful concept that makes your code more functional and predictable.

Even a simple calculation or a conditional block can return a value.

Try running this example:

object Main {
  def main(args: Array[String]): Unit = {
    val x = 5 + 3
    println(s"The value of x is: $x")

    val message = if (x > 7) "Greater than 7" else "Not greater than 7"
    println(message)
  }
}

`val`: Immutable Values

When you declare a variable using val, you are creating an immutable value. This means once it's assigned, its value cannot be changed.

Immutability is a cornerstone of functional programming and helps prevent unexpected side effects, making your code safer and easier to reason about.

Try it out:

object Main {
  def main(args: Array[String]): Unit = {
    val greeting = "Hello, Coddy!"
    println(greeting)
    // greeting = "New message" // This would cause a compile error!
  }
}

`var`: Mutable Variables

Sometimes you need a variable whose value can change. For this, Scala provides var for mutable variables.

While useful, it's a good practice in Scala to favor val over var whenever possible to embrace immutability and functional style.

See how `var` works:

object Main {
  def main(args: Array[String]): Unit = {
    var counter = 0
    println(s"Initial counter: $counter")
    counter = counter + 1
    println(s"New counter: $counter")
  }
}

Numbers: Int, Long, Double

Scala supports common numeric types. The compiler often infers the type, but you can specify it.

  • Int: For whole numbers (e.g., 10)
  • Long: For larger whole numbers (suffix L, e.g., 10000000000L)
  • Double: For floating-point numbers (decimals, e.g., 3.14)

Here's an example:

object Main {
  def main(args: Array[String]): Unit = {
    val anInt = 42
    val aLong = 1234567890123L
    val aDouble = 3.14159

    println(s"Int: $anInt")
    println(s"Long: $aLong")
    println(s"Double: $aDouble")
  }
}

Boolean and Char Types

Beyond numbers, Scala has types for truth values and single characters:

  • Boolean: Represents truth values, either true or false.
  • Char: Stores a single character, enclosed in single quotes (e.g., 'A').

These are fundamental for logic and text processing.

Example:

object Main {
  def main(args: Array[String]): Unit = {
    val isActive = true
    val initial = 'C'

    println(s"Is active? $isActive")
    println(s"Initial character: $initial")
  }
}

Strings and Text

The String type is used for sequences of characters, or text. Strings are immutable in Scala, just like in Java.

A very useful feature is String Interpolation, which allows you to embed expressions directly within string literals using an s prefix and $ for variables.

Check this out:

object Main {
  def main(args: Array[String]): Unit = {
    val name = "Coddy"
    val age = 3

    val greeting = s"Hello, my name is $name and I am $age years old."
    println(greeting)

    val mathResult = s"Two plus two is ${2 + 2}"
    println(mathResult)
  }
}

Basic Arithmetic Operators

Scala provides standard arithmetic operators for performing calculations with numbers:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • % (Modulo - remainder of division)

These operators work as you'd expect, returning a new numeric value.

Let's do some math:

object Main {
  def main(args: Array[String]): Unit = {
    val a = 10
    val b = 3

    println(s"Addition: ${a + b}")
    println(s"Subtraction: ${a - b}")
    println(s"Multiplication: ${a * b}")
    println(s"Division: ${a / b} (integer division)")
    println(s"Modulo: ${a % b}")

    val c = 10.0
    val d = 3.0
    println(s"Float Division: ${c / d}")
  }
}

Comparison Operators

Comparison operators are used to compare two values and always return a Boolean (true or false).

  • == (Equal to)
  • != (Not equal to)
  • < (Less than)
  • > (Greater than)
  • <= (Less than or equal to)
  • >= (Greater than or equal to)

They are essential for control flow and decision-making.

object Main {
  def main(args: Array[String]): Unit = {
    val x = 10
    val y = 5

    println(s"x == y: ${x == y}")
    println(s"x != y: ${x != y}")
    println(s"x > y: ${x > y}")
    println(s"x <= y: ${x <= y}")
  }
}

Quick Check: Variables & Operators

Consider the following Scala code snippet:

object Main {
  def main(args: Array[String]): Unit = {
    val num1 = 7
    var num2 = 3
    num2 = num1 * 2
    val finalResult = num1 + num2 - 5
    println(finalResult)
  }
}

Recap: Syntax & Types

Great job! In this lesson, you've learned the fundamentals of Scala's basic syntax, including the use of expressions and the optional nature of semicolons.

We explored how to declare variables using val for immutable values and var for mutable ones. You also got familiar with common data types like Int, Long, Double, Boolean, Char, and String, including handy String Interpolation.

Finally, you practiced using basic arithmetic and comparison operators to perform calculations and logical checks. Keep practicing these basics as they are the building blocks for more complex Scala programs!

자주 묻는 질문

“기본 구문과 타입” 강의는 무료인가요?

네 — “기본 구문과 타입” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 3개의 강의가 포함되어 있습니다.

“기본 구문과 타입”에서 뭘 배우나요?

Scala의 기본 구문, 변수 선언(val/var), 일반적인 데이터 타입과 기본 연산자를 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 2번째 강의입니다.

“기본 구문과 타입” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Scala 시작하기
  2. 기본 구문과 타입
  3. 제어 구조와 함수
← Scala for Backend Engineering & Functional Programming(으)로 돌아가기