Scala operators
1. 함수와 메소드
- 코드 블럭을 묶어서 같은 결말 또는 같은 업무로 실행하고 싶을 떄 만든다.
객체지향은 객체를 정의하여 내부에 내용들을 정의하고 추상화한다.
-
스칼라에서는 function 들이 이미 만들어진 객체이다.
-
function은 변수에 저장할 수 있다.
- 스칼라에서는 모든 것들이 객체다.
2. 연산자
| Operator | Name | Example |
|---|---|---|
| + | Addition | x + y |
| - | Subtraction | x - y |
| * | Multiplication | x * y |
| / | Division | x / y |
| % | Modulus | x % y |
| == | Equal | x == y |
| != | Not equal | x != y |
| > | Greater than | x > y |
| < | Less than | x < y |
| ≥ | Greater than or equal to | x ≥ y |
| ≤ | Less than or equal to | x ≤ y |
| && | Returns True if bvoth statements are true | x >= 4 && x <= 8 y |
| || | Return True if one of the statements is true | x > 100 || x < 50 |
| ! | Return the opposite of the evaluated result. Return True if false and False if true | !(x > 100 || x < 50) |
| & | Binary AND | x & y |
| | | Binary OR | x | y |
| ^ | Binary XOR | x ^ y |
| ~ | Binary One's Complement | ~x |
| << | Binary Left-Shift | x << 2 |
| >> | Binary Right-Shift | x >> 2 |
| >>> | Shift-Right Zero-Fill | x >>> 2 |
| = | Simple assignment | x = 6 |
| += | Add and Assignment | x += 4 |
| -= | Subtract and Assignment | x -= 4 |
| *= | Multiply and Assignment | x *= 4 |
| /= | Divide and Assignment | x /= 4 |
| %= | Modulus and Assignment | x %= 4 |
| &= | Bitwise AND and Assignment | x &= 4 |
| |= | Bitwise OR and Assignment | x += 4 |
| ^= | Bitwise XOR and Assignment | x ^= 4 |
| <≤ | Left-shift and Assignment | x <≤ 4 |
| >≥ | Right-shift and Assignment | x >≥ 4 |
3. 예제
import scala.math._
sqrt(2)
val myHello = "hello"
// myHello(4) // sugar coating
myHello.apply(4)
// 스칼라의 모든 것은 객체이다.
// 심지어 연산 기호 조차도 객체이다.
1.+(5) // 1 + 1 은 1.+(5) 의 sugar coating 이다.
// res172: Int = 6
val one: Int= 1
one.to(10)
// one: Int = 1
// res174: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val x : BigInt = 123456789
x * x * x * x
// x.*(x).*(x).*(x)
// x: scala.math.BigInt = 123456789
// res176: scala.math.BigInt = 232305722798259244150093798251441
5 / 2
5.0 / 2.0
// res182: Int = 2
// res184: Double = 2.5
val a = 12
val b = 5
~a
a & b
a | b
a ^ b
// a: Int = 12
// b: Int = 5
// res192: Int = -13
// res193: Int = 4
// res194: Int = 13
// res195: Int = 9
4. 스칼라 연산자 순위
| Category | Operator | Associativity |
|---|---|---|
| Postfix | () [] | Left to Right |
| Unary | ! ~ | Right to Left |
| Multiplicative | * / % | Left to Right |
| Additive | +- | Left to Right |
| Shift | >> >>> << | Left to Right |
| Relational | > ≥ < ≤ | Left to Right |
| Equality | == != | Left to Right |
| Bitwise AND | & | Left to Right |
| Bitwise XOR | ^ | Left to Right |
| Bitwise OR | | | Left to Right |
| Locgical AND | && | Left to Right |
| Logical OR | || | Left to Right |
| Assignment | = += -= *= /= %= >≥ <≤ &= ^= |= | Right to Left |
| Comma | , | Left to Right |