페이지

2015년 11월 3일 화요일

Scala2e Chapter5 Basic Types and Operations 5.3 Operators are methods

Scala provides a rich set of operators for its basic types.

class Int Contains a method named + that takes an Int and returns an Int result.

scala> val sum = 1 + 2 // Scala invokes (1).+(2)
sum: Int = 3

scala> val sumMore = (1).+(2)
sumMore: Int = 3

You call a method that takes multiple arguments using operator notation, you have to place those arguments in parentheses.

scala> val s = "Hello, world!"
s: java.lang.String = Hello, world!
scala> s indexOf 'o' // Scala invokes s.indexOf(’o’)
res0: Int = 4

scala> s indexOf ('o', 5) // Scala invokes s.indexOf(’o’, 5)
res1: Int = 8

Any method can be an operator
In Scala operators are not special language syntax: any method can be an operator. What makes a method an operator is how you use it. When you write "s.indexOf('o'), indexOf is not an operator. But when you write "s indexOf 'o', indexOf is an operator, because you're using it in operator notation.

Scala also has two other operator notations: prefix and postfix.
In prefix notation, you put the method name before the object on which you are invoking the method, for example, the '-' in -7. In postfix notation, you put the method after the object, for example, the "toLong" in "7 toLong".

In contrast to the infix operator notation = in which operatior take two operands. on th the left and the other to the right - prefix and postfix operators are unary: they take just on operand. In prefix notation, the operand is to the right of the operator. Some examples of prefix operators are -2.0, ! found, and ~0xFF.

scala> -2.0          // Scala invokes (2.0).unary_-
res2: Double = -2.0
scala> (2.0).unary_-
res3: Double = -2.0

The only identifiers that can be used as prefix operators are +, -, !, and ~.
Thus, if you define a method anmed unary_!, you could invoke that method on a value or variable of the appropriate type useing prefix operator notation, such as !p.

Postfix operators are methods that take no arguments, when they are invoked without a dot or parentheses. In Scala, you can leave off empty parentheses on method calls. The convention is that you include parentheses if the method has side effects, such as println(), but you can leave them off if the method has no side effects. such as toLowerCase invoked on a String:

scala> val s = "Hello, world!"
s: java.lang.String = Hello, world!
scala> s.toLowerCase
res4: java.lang.String = hello, world!

scala> s toLowerCase
res5: java.lang.String = hello, world!

댓글 없음: