Code Examples for

Programming in Scala

Return to chapter index

11 Scala's Hierarchy

Sample run of chapter's interpreter examples

11.1 Scala's class hierarchy


final def ==(that: Any): Boolean final def !=(that: Any): Boolean def equals(that: Any): Boolean def hashCode: Int def toString: String
scala> new Int
<console>:5: error: class Int is abstract; cannot be instantiated new Int ^
scala> 42.toString res1: java.lang.String = 42 scala> 42.hashCode res2: Int = 42 scala> 42 equals 42 res3: Boolean = true
scala> 42 max 43 res4: Int = 43 scala> 42 min 43 res5: Int = 42 scala> 1 until 5 res6: Range = Range(1, 2, 3, 4) scala> 1 to 5 res7: Range.Inclusive = Range(1, 2, 3, 4, 5) scala> 3.abs res8: Int = 3 scala> (-3).abs res9: Int = 3

11.2 How primitives are implemented


// In file hierarchy/Ex1.java // This is Java boolean isEqual(int x, int y) { return x == y; } System.out.println(isEqual(421, 421));
// In file hierarchy/Ex2.java // This is Java boolean isEqual(Integer x, Integer y) { return x == y; } System.out.println(isEqual(421, 421));
scala> def isEqual(x: Int, y: Int) = x == y isEqual: (Int,Int)Boolean scala> isEqual(421, 421) res10: Boolean = true scala> def isEqual(x: Any, y: Any) = x == y isEqual: (Any,Any)Boolean scala> isEqual(421, 421) res11: Boolean = true
scala> val x = "abcd".substring(2) x: java.lang.String = cd scala> val y = "abcd".substring(2) y: java.lang.String = cd scala> x == y res12: Boolean = true
scala> val x = new String("abc") x: java.lang.String = abc scala> val y = new String("abc") y: java.lang.String = abc scala> x == y res13: Boolean = true scala> x eq y res14: Boolean = false scala> x ne y res15: Boolean = true

11.3 Bottom types


scala> val i: Int = null <console>:4: error: type mismatch; found : Null(null) required: Int
def error(message: String): Nothing = throw new RuntimeException(message)
// In file hierarchy/Ex3.scala def divide(x: Int, y: Int): Int = if (y != 0) x / y else error("can't divide by zero")

11.4 Conclusion

For more information about Programming in Scala (the "Stairway Book"), please visit:

http://www.artima.com/shop/programming_in_scala

and:

http://booksites.artima.com/programming_in_scala

Copyright © 2007-2008 Artima, Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.