楼主: ReneeBK
730 4

[Lecture Notes]Object-Oriented Software Development [推广有奖]

  • 1关注
  • 62粉丝

VIP

已卖:4897份资源

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49635 个
通用积分
55.6937
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57805 点
帖子
4005
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

楼主
ReneeBK 发表于 2016-8-20 01:18:42 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
http://homepage.cs.uiowa.edu/~ti ... ng15/lectures.shtml
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:Development Oriented software Lecture Develop Software

沙发
ReneeBK 发表于 2016-8-20 01:20:55
  1. /*
  2.   CS:2820 Object Oriented Software Development
  3.   Spring 2015
  4.   The University of Iowa
  5.    
  6.    Instructor: Cesare Tinelli
  7. */


  8. /* Scala examples seen in class */

  9. /* static scoping rules */

  10. val a = 10

  11. def f (x:Int) = a + x

  12. f(4)

  13. // *new* immutable variable a, distinct from the previous one
  14. val a = 100

  15. // the new a shadows the old one
  16. a

  17. // however, the old one is unchanged
  18. f(4)


  19. // blocks can contain both expression *and* (variable/method) definitions

  20. // variable k1 is visible only in the block in which it is declared

  21. {val k1 = 4
  22. k1*k1
  23. }

  24. k1 // error

  25. // within
  26. {val x = 4
  27. val x = 5
  28. x
  29. }


  30. // local declarations shadow less local ones
  31. val k = 1
  32. {val k = 2;
  33.   {val k = 3
  34.    println(k)
  35.   }
  36. println(k)
  37. }
  38. println(k)

  39. // there is no shadowing within the same block though
  40. {val x = 4
  41. val x = 5 // will generate an error
  42. x
  43. }


  44. // method definitions can have local scope too
  45. {def h(x:Int) = x + 1
  46. h(9)
  47. }

  48. h(9)  // error

  49. // this implies that methods can be defined locally
  50. // within other methods

  51. def f (x:Int) = {
  52. def square (x:Int) = x * x
  53. def double (x:Int) = x + x

  54. square(x) - double(x)
  55. }


  56. // Scala has while "statements" too.
  57. // As in the case of if, they are actually expressions of type Unit.
  58. // While can be seen a mixfix operator with two arguments:
  59. //
  60. //    while (_) _
  61. //
  62. // the first argument takes an expression of type bool,
  63. // the second takes any expression
  64. var j = 10

  65. while (j > 0)  j = j - 1


  66. val u = while (j > 0)  j = j - 1

  67. // the second argument of while can be a block
  68. j = 6

  69. while (j > 0) {
  70.         println(j)
  71.         j = j - 1
  72. }  

  73. // a block of two expressions, both of type Unit
  74. {
  75.         j = 8
  76.         while (j > 0) {
  77.          println(j)
  78.          j = j - 1
  79.         }
  80. }

  81. // The body of a method can be a block
  82. def print_range(m:Int, n:Int) = {
  83.   var i = m
  84.   println()
  85.   while (i <= n) {
  86.     print(i + " ")
  87.     i = i + 1
  88.   }
  89.   println()
  90. }

  91. print_range(4,9)


  92. // imperative-style definition of factorial function
  93. def fact (n:Int) = {
  94.   var i = n
  95.   var f = 1
  96.   while (i > 0) {
  97.     f = f * i
  98.     i = i - 1
  99.   }
  100.   f
  101. }

  102. // functional style, recursive definition of factorial
  103. def rfact (n:Int) = if (n <= 1) 1 else n * rfact(n-1)



  104. // declaring the return type of recursive methods is mandatory
  105. def rfact (n:Int):Int = {
  106. if (n <= 1)
  107.   1
  108. else
  109.   n * rfact(n-1)
  110. }





  111. /* Pattern matching */

  112. val t = (3,5,2)

  113. // declare three new variables x1,x2,x3;
  114. // the value of xi is the value of t's i-th component;
  115. // the pattern (x1,x2,x3) is matched against (3,5,2)
  116. val (x1,x2,x3) = t

  117. // _ is for "don't care" positions
  118. val (y1,y2,_) = t

  119. // pattern matching can be used with nested patterns
  120. val t = ((2,3),5,(6,2))

  121. val (_, x, _) = t
  122. val (_, _, (x,_)) = t


  123. // patterns are extremely useful with the match construct:
  124. //
  125. //    (_ match {case _ => _ ... case _ => _})
  126. //
  127. // the first argument of match is match agains the pattern given
  128. // between case and => ;
  129. // patterns are checked one at a time, top-down;
  130. // the value of the whole match construct is the value of the expression
  131. // on the right of the matching pattern
  132. var n = 1

  133. n match {
  134.   case 0 => "zero"
  135.   case 1 => "one"
  136.   case _ => "other"
  137. }
  138. // All right-hand sides of a 'case' clause must be of the same type


  139. // if all cases fail an exception is raised
  140. n match {
  141.   case 0 => "zero"
  142. }


  143. // match and patterns allow one to write cleaner and more compact code
  144. def convert (n:Int) =
  145.   n match {
  146.    case 0 => "zero"
  147.    case 1 => "one"
  148.    case _ => "other"
  149.   }
  150.   
  151. // the bodies of the case statements can be any expression (in particular a block)
  152. // but, like in the the two branches of the if construct, they all have to be of
  153. // same type  
  154. def p (n: Int) =
  155.   n match {
  156.     case 0 => {
  157.       print("You entered ")
  158.       println("zero")
  159.     } // type of this is Unit
  160.     case _ => {
  161.      print("You did not enter ")
  162.      println("zero")
  163.     } // type of this is Unit
  164.   }
  165.   
  166. // patterns can be complex and nested
  167. var v = (1, 2)

  168. v match {
  169.   case (0, 0) => "a"
  170.   case (0, _) => "b"
  171.   case (_, 0) => "c"
  172. }

  173. // bothZero returns "OK" if both of its arguments are 0
  174. // Otherwise it returns "NotOK"
  175. // common (bad) coding style
  176. def bothZero (x1:Int, x2:Int) = {
  177.   if (x1 == 0) {
  178.     if (x2 == 0)
  179.       "OK"
  180.     else
  181.       "NotOK"
  182.   }
  183.   else
  184.     "NotOK"
  185. }
  186.   
  187. // same method but using match

  188. def bothZero (x1:Int, x2:Int) =
  189.   (x1, x2) match {
  190.     case (0, 0) => "OK"
  191.     case _ => "NotOK"
  192.   }


  193. // the input here is already a pair that can be pattern matched
  194. // directly
  195. def bz (p:(Int, Int)) =
  196.   p match {
  197.     case (0, 0) => true
  198.     case _ => false
  199.   }

  200. def and (p:(Boolean, Boolean)) =
  201.   p match {
  202.     case (true, y) => y
  203.     case (false, _) => false
  204.   }
  205. // the scope of a pattern variable in a case is the body of that case

  206. def and (p:(Boolean, Boolean)) =
  207.   p match {
  208.     case (true, y) => y
  209.     case (false, _) => y // y is undefined here
  210.   }


  211. // factorial with match
  212. def fact (n:Int):Int =
  213.   n match {
  214.     case 0 => 1
  215.     case _ => n * fact(n - 1)
  216.   }
  217.   
  218. // you can match several values at the same time by putting them into a tuple

  219. (0 < 1, 1 == 1) match {
  220.   case (true, y) => y
  221.   case (false, _) => false
  222. }
  223.         
  224.         
  225. // the match construct too builds expressions

  226. val r = (0 < 1, 1 == 1) match {
  227.          case (true, y) => y
  228.          case (false, _) => false
  229.         }
复制代码

藤椅
ReneeBK 发表于 2016-8-20 01:21:55
  1. /*
  2.   CS:2820 Object Oriented Software Development
  3.   Spring 2015
  4.   The University of Iowa
  5.    
  6.    Instructor: Cesare Tinelli
  7. */

  8. /* Scala examples seen in class */



  9. /* Collections: Lists */

  10. // lists are finite sequences of elements
  11. val l = List(1, 2, 3)

  12. // Main list methods
  13. l.head
  14. l.tail
  15. l.length

  16. // individual elements can be accessed with this syntax
  17. // with indices starting at zero (like in arrays)

  18. l(0)  // first element of l

  19. l(3)  // fourth element of l


  20. // a list can be built with elements of *any* type,
  21. // but all elements must be of the *same* type
  22. List('a', 'b')

  23. List("hi", "there")

  24. List((1, 2), (1, 4))

  25. List(List(1, 2), List(1, 4, 3))

  26. List(1, "a")   // types as a list of Any


  27. val l1 = List(1, 2, 3)
  28. val l2 = List(1, 2, 3)

  29. // list identity
  30. l1 eq l2   

  31. val l3 = l1

  32. l1 eq l3

  33. // structural equality
  34. l1 == l2  

  35. // order and number of occurrences of elements matters for equality
  36. List(1,2,3) == List(2,1,3)

  37. List(1,2) == List(1,2,2)



  38. // Empty list, prints as List()
  39. Nil

  40. // Evaluates to Nil
  41. List()

  42. Nil eq List()


  43. // bad practice, gives you a list of elements of type Nothing.
  44. val l = List()

  45. // recommended, specify the element type of an empty list explicitly
  46. val il = List[Int]()

  47. var x = List("a", "b")

  48. // Causes an implicit conversion of 1 and 2 to Long.
  49. var y = List[Long](1, 2)


  50. // if T1 and T2 are different types,
  51. // List[T1] is a different type from List[T2]
  52. // no implict conversions are defined for them
  53. x = il

  54. y = il


  55. // Lists are built by increasingly adding elements in front
  56. // of Nil with the "cons" operator ::
  57. val x = 6 :: Nil

  58. val y = 5 :: x

  59. // note that x is unchanged
  60. x

  61. y.tail eq x

  62. // :: is right associative.
  63. 3 :: 4 :: Nil
  64. // same as
  65. 3 :: (4 :: Nil)

  66. // List(3, 4) can be understood as syntactic sugar for
  67. 3 :: (4 :: Nil)



  68. 3 :: 4  // error, right-hand argument not a list

  69. // can mix and match notation
  70. 3 :: List(4)

  71. // note type here
  72. List(7) :: Nil



  73. val l = List(1, 2, 3)

  74. // invariant defining head and tail in terms of ::
  75. // for any non-empty list
  76. //
  77. (l.head :: l.tail) == l



  78. // pattern matching also works with ::
  79. val h :: t = l

  80. // why it works: l is really 1 :: (2 :: (3 :: Nil))
  81. val h :: t = 1 :: (2 :: (3 :: Nil))

  82. // deeper patters for lists with at least two elements
  83. val x1 :: x2 :: t = l

  84. val x1 :: x2 :: x3 :: t = l

  85. val x1 :: x2 :: x3 :: x4 :: t = l // fails because l has < 4 elements

  86. // 'List' syntax can also be used for pattern matching
  87. val List(x1, x2, x3) = l

  88. // fails because l has length 3
  89. val List(x1) = l

  90. // also fails
  91. val List(x1, x2) = List("a")



  92. // recursive definition of length function for lists
  93. // based on navigating the list structure.
  94. // If l is empty its length is 0. If l is non-empty,
  95. // and so has a tail t, its lenght is 1 + the length of t
  96. //
  97. def len (l: List[Int]): Int =
  98.   l match {
  99.     case Nil    => 0
  100.     case _ :: t => 1 + len(t)
  101.   }
  102.   
  103.   
  104. len(List(1, 1, 1))

  105. // min returns the minimun element of an non-empty integer list,
  106. // it raises an exception with empty lists
  107. //
  108. // if l has only one element n, the minimum is n
  109. // if l has at least two elements its miminum is the smaller
  110. // between l's head and the minimun of l's tail.
  111. //
  112. def min (l:List[Int]):Int =
  113.   l match {
  114.     case Nil => throw new IllegalArgumentException
  115.     case n :: Nil => n
  116.     case n :: t => {
  117.       val m = min(t)
  118.       if (n < m) n else m
  119.     }
  120.   }

  121. // concat contatenates two lists
  122. def concat(l:List[Int], m:List[Int]):List[Int] =
  123.   l match {
  124.     // when l is empty, its concatenation with m is just m
  125.     case Nil  => m
  126.     // when l has a head h and a tail t, its contatenation with m
  127.     // is obtained by inserting h in front of the contatenation
  128.     // of t with m
  129.     case h :: t => h :: concat(t, m)
  130.   }

  131. concat(List(1, 2), List(3, 4, 5))

  132. // the effect of concat is achieved with the predefined overloaded operator ++
  133. List(1,2) ++ List(3,4,5)

  134. // reverse reverses a list
  135. def reverse (l:List[Int]):List[Int] =
  136.   l match {
  137.     // when l is empty it is its own reverse
  138.     case Nil => l
  139.     // when l has a head h and a tail t, its reverse is the contatenation
  140.     // of the reverse of t with a list containing just h
  141.     case h :: t => {
  142.       val rt = reverse(t)
  143.       val lh = List(h)
  144.       concat(rt, lh)
  145.     }
  146.   }

  147. reverse(List(3, 4, 5))

  148. // more compact version of the implementation above
  149. // both version are inefficient because each reverse(t) is
  150. // scanned linearly by concat each time
  151. def reverse (l:List[Int]):List[Int] =
  152.   l match {
  153.     case Nil  => l
  154.     case h :: t => concat(reverse(t), List(h))
  155.   }
  156.   
  157. // this reverse uses a local auxiliary function rev
  158. // rev is "tail-recursive", it builds the reverse of l as it scans it
  159. // by incrementally moving its elements into an initially empty list rl.
  160. // l is scanned only once
  161. def reverse (x:List[Int]):List[Int] = {

  162.   def rev (l:List[Int], rl:List[Int]):List[Int] =
  163.   l match {
  164.     // when l has a head h and a tail t, put h in front of rl
  165.     // and continue with t and h::rl
  166.     case h :: t => rev(t, h :: rl)
  167.     // when l is Nil, rl contains by construction the reverse
  168.     // of the original list
  169.     case Nil => rl
  170.   }

  171.   rev(x, Nil)
  172. }
复制代码

板凳
ReneeBK 发表于 2016-8-20 01:23:24
  1. /*
  2.   CS:2820 Object Oriented Software Development
  3.   Spring 2015
  4.   The University of Iowa
  5.    
  6.    Instructor: Cesare Tinelli
  7. */



  8. /* Collection types: Arrays */

  9. // creates an array with 5 elements and calls it a
  10. val a = new Array(5)

  11. // more typically, one specifies the element type as well;
  12. // the array elements start with a type-dependent default value
  13. val a = new Array[Double](5)

  14. a[1]  // standard notation *not* used in Scala

  15. a(1)  // Scala's notation for array access

  16. a(0) = 2.5  //  array update

  17. a(5)  // generates out of bound error

  18. // generates an Array[Int] of length 3 and elements 10,11, and 12;
  19. // element type Int is inferred
  20. Array(10, 11, 12)

  21. val a = Array(10, 11, 12)

  22. // 3 different ways to generate an Array[Long]
  23. // from Int initial values
  24. val a = Array[Long](10, 11, 12)  // preferred one

  25. val a:Array[Long] = Array(10, 11, 12)

  26. val a = Array(10:Long, 11, 12)



  27. // note the tricky difference

  28. val a =     Array[Long](10)  // a is an Array[Long] with one element: 10

  29. val b = new Array[Long](10)  // n is an Array[Long] with 10 elements

  30. // array length
  31. a.length

  32. // multidimentional arrays are arrays of arrays
  33. val m = new Array[Array[Int]](10)

  34. val m = Array(Array(1, 2, 3),
  35.               Array(4, 5, 6),
  36.               Array(7, 8, 9),
  37.               Array(10, 11, 12))

  38. m(2)(1) // no special syntax for matrix access



  39. /* Scala examples seen in class */

  40. /* Built-in control structures */  

  41. /* for loops */

  42. // The for loop is an expression of type Unit
  43. // It can be seen as a mixfix operator with two arguments:
  44. //
  45. //   for (_) _
  46. //
  47. // The second argument (the "body") is any expression.
  48. // The first argument is a sequence of one or more *generators*
  49. // separated by ';'
  50. //
  51. // A generator is an expression of the form  _ <- _ where the first
  52. // argument is a pattern and the second is an expression of a collection
  53. // type (Range, List, Array, ...)

  54. // below, the pattern 3 is matched against each element of the list.
  55. // each time there is a match, the body of for is evaluated
  56. for (3 <- List(1,3,4,3,5,3,6,3))  println("Hi")

  57. // as in the match and val constructs, patterns can contain variables
  58. for (i <- List(1,2,14,52,7,10)) println("high five")

  59. // any variables in the pattern have local scope within the for
  60. for (i <- List(1,2,14,52,7,10)) println("i = " + i)

  61. i // gives an error


  62. // patterns in a generator can be arbitrarily complex, depending
  63. // on the type of the collection
  64. val l = List((1,2), (1,4), (6,7), (3,6))

  65. for ( (i, j) <- l )  println("i = " + i + ", j = " + j)  

  66. for ( (i, _) <- l )  println(i) // ignores the second component of each pair

  67. for ( (1, j) <- l )  println(j) // only matches pairs starting with 1


  68. // *any collection* type can be used in a generator
  69. for (i <- Array(1.2, 2.5, 4.5, 7.1)) println("i = " + i)

  70. for (i <- Set(1,2,4,5,7,10,4)) println("i = " + i)

  71. // even strings, which are seen as the collection of their characters
  72. for (i <- "abcd") println("i = " + i)

  73. // ranges are sequences of consecutive integers
  74. val r = Range(1,5) // contains values 1, 2, 3, 4

  75. for (i <- r) println("i = " + i)

  76. // Expression   1 to 4   is the same as Range(1,5)
  77. for (i <- 1 to 4) println("i = " + i)


  78. // Putting more than one generator has the effect of nested for loops
  79. for (i <- 1 to 2; j <- 1 to 3) println("i = " + i + ", j = " + j)

  80. // the above for has the same effect as
  81. for (i <- 1 to 2) {
  82.   for (j <- 1 to 3) println("i = " + i + ", j = " + j)
  83. }

  84. // and it can also be written as
  85. for {
  86.   i <- 1 to 2
  87.   j <- 1 to 3
  88. } println("i =" + i + ", j = " + j)


  89. // a generator can be optionally followed by a *filter* of the form: if b
  90. // where b is a Boolean expression.
  91. // the matched value is used if and only if b evaluates to true
  92. for (i <- List(1,9,2,4,5,7,10) if i > 4) println("i = " + i)

  93. val l = List((1,2), (1,4), (6,7), (3,6))

  94. for ( (i,j) <- l if j == 2*i )
  95.   println((i,j))


  96. for {
  97.   c1 <- "hi"
  98.   c2 <- "fifi"
  99.   if c1 == c2
  100. } println("character match found for letter " + c1)


  101. // BTW, matching filters can be used with the match construct too
  102. val l = List(2, 1, 3)

  103. l match {
  104.         case x :: y :: t if (x > y) =>  y :: x :: t
  105.         case _  =>  l
  106. }
  107. // the first case applies only if l has at least two elements *and*
  108. // its first element is greater than the second


  109. // this version of reverse scans the input list x using
  110. // a for loop instead of a recursive call,
  111. // each element of x is inserted into an initialy empty list;
  112. // a mutable variable is necessary to store the growing reversed list
  113. //
  114. def reverse(x:List[Int]):List[Int] = {
  115.   var l = List[Int]()
  116.   for (h <- x)  l = h :: l
  117.   l
  118. }
复制代码

报纸
ReneeBK 发表于 2016-8-20 01:26:23
  1. /*
  2.   CS:2820 Object Oriented Software Development
  3.   Spring 2015
  4.   The University of Iowa
  5.    
  6.    Instructor: Cesare Tinelli
  7. */

  8. /* Classes and class instances */



  9. /* User-defined classes */

  10. // One can define new classes with the construct of the form
  11. //
  12. //  class Name(a1,...,an) { ... }
  13. //
  14. // where Name is an identifier for the class,
  15. // a1, ..., an for n >= 0  are any values
  16. // { ... } is the "body" of the class definition


  17. class A() {}  

  18. // equivalently:
  19. class A {}

  20. // or even
  21. class A



  22. // Every class C defines a type C
  23. // Each *instance* of a class C, which we call an object,
  24. // is a value of type C

  25. // objects are created with the construct (new _)

  26. new A


  27. val a1 = new A

  28. val a2 = new A

  29. a1 == a2

  30. a1 eq a2


  31. // The body of a class declaration is a block and
  32. // can contain anything allowed in a block
  33. // Any declarations within the body have only local scope in there

  34. class B {
  35.   var x = 1         
  36.   val s = "abc"

  37.   def m(n: Int) = x + n
  38. }

  39. // variables in a class are also called "fields"

  40. // The fields of an instance of class B constitute's
  41. // the object's *internal state*.

  42. // Fields and methods can be accessed using the common
  43. // dot notation

  44. val b = new B

  45. b.x

  46. b.s

  47. b.m(10)

  48. // the value stored in a mutable field can be modified
  49. // with assignments
  50. b.x = 7

  51. b.m(10)

  52. // Whatever expressions are in a class' body they are
  53. // evaluated at object creation time
  54. // The effect of this evaluation is a new object
  55. class B {
  56.   println("Starting creating new object of class B")
  57.   var x = 1
  58.   val s = "abc"

  59.   def m(n: Int) = x + n

  60.   def g = 33  // parameterless method

  61.   println("Done creating new object of class B")
  62. }

  63. new B



  64. /* Operational difference between fields and
  65.    parameterless methods
  66. */

  67. // The value of an object's field is determined at object
  68. // creation time. In contrast, a parameterless method is
  69. // still a method, so its returned value is computed
  70. // anew each time the method is called.

  71. class A {
  72.   var x = 0
  73.   val y = x + 1  // y will be initialized to 1 and stay so
  74.   def f = x + 1  // the value returned by f each time depends
  75.                  // on the current value of x
  76. }

  77. val a = new A

  78. a.x
  79. a.y  // evaluates to 1
  80. a.f  // evaluates to 1

  81. a.x = 4

  82. a.y  // still evaluates to 1
  83. a.f  // evaluates to 5


  84. // A class declaration can have input parameters
  85. class Point(x0:Double, y0:Double) {
  86.   val x = x0
  87.   val y = y0
  88. }

  89. val p = new Point(4.5, 3.9)

  90. p.x

  91. p.y

  92. // input parameters are used only at object creation time

  93. p.x0   // error

  94. // but they can turned into fields as in the example below

  95. class Point(val x:Double, val y:Double) {}

  96. // x, y are both input parameters and (immutable) fields

  97. val p = new Point(6.5, 3.1)

  98. p.x

  99. p.y

  100. // "class Point(val x:Double, val y:Double) {}" is just
  101. // an abbreviation for a declaration of the form
  102. class Point(x0:Double, y0:Double) {
  103.   val x = x0
  104.   val y = y0
  105. }




  106. // Fields and methods are exposed by default: they are "public"
  107. // They can be hidden inside by declaring them as "private"
  108. // private fields and methods are visible only by objects of the same class
  109. class Point(x0:Double, y0:Double) {
  110.   private val x = x0
  111.   private val y = y0

  112.   def coincidesWith (other: Point) =
  113.     (x == other.x) && (y == other.y)
  114.     // other.x and other.y are visible by current point
  115. }



  116. val p1 = new Point(6.5, 3.1)

  117. p1.x  //  error

  118. val p2 = new Point(6.5, 3.1)

  119. p1.coincidesWith(p2)

  120. p1 == p2

  121. // note less verbose alternative notation
  122. p1 coincidesWith p2


  123. // more abbreviations:
  124. class Point(private val x:Double, private val y:Double) {
  125. }
  126. // abbreviates something like
  127. class Point(x0:Double, y0:Double) {
  128.   private val x = x0
  129.   private val y = y0
  130. }



  131. // inside a class method definition the object that receives the calls
  132. // can be referred to by 'this'
  133. class Point(private val x:Double, private val y:Double) {

  134.   def coincidesWith (other:Point) =
  135.     (this.x == other.x) && (y == other.y)
  136.     // 'this.x' is the same as just x

  137.   def sameAs (other:Point) =
  138.     this eq other
  139. }

  140. val p1 = new Point(6.5, 3.1)
  141. val p2 = new Point(6.5, 3.1)

  142. p1 sameAs p2

  143. p1 sameAs p1

  144. val p3 = p1

  145. p1 sameAs p3


  146. // 'this' can be used also to define alternative object constructors

  147. class Point(val x:Double, val y:Double) {

  148.   // new object constructor, taking only one parameter
  149.   def this(x: Double) =
  150.     this(x, x) // call to basic constructor, implicitly defined
  151.                // by parameters (x0:Double, y0:Double) above

  152.   // another constructor, taking no parameters
  153.   def this() =
  154.     this(0.0)  // call to unary constructor above
  155. }

  156. val p1 = new Point(4.1, 5.9)

  157. val p2 = new Point(1.7)

  158. val p3 = new Point

  159. p2.x
  160. p2.y

  161. p3.x
  162. p3.y


  163. // methods called 'apply' can be called with shorthand syntax
  164. class Point(private val x:Double, private val y:Double) {
  165.   
  166.   def apply(i:Int) =
  167.     i match {
  168.       case 0 => x
  169.       case 1 => y
  170.       case _ => throw new IllegalArgumentException
  171.   }
  172. }

  173. val p = new Point(4.6, 9.1)

  174. p.apply(0)
  175. // can be abbreviated as
  176. p(0)


  177. // operator symbols like +, -, ++, *, **, etc. can be used
  178. // as method names in user-defined classes
  179. class Point(private val x:Double, private val y:Double) {
  180.   def +(other: Point) =
  181.     new Point(x + other.x, y + other.y)

  182.   def -(other: Point) =
  183.     new Point(x - other.x, y - other.y)

  184.   def apply(i:Int) =
  185.     i match {
  186.       case 0 => x
  187.       case 1 => y
  188.       case _ => throw new IllegalArgumentException
  189.   }
  190. }

  191. val p1 = new Point(4.0, 9.0)
  192. val p2 = new Point(3.0, 1.0)

  193. val p = p1.+(p2)

  194. p(0)
  195. p(1)

  196. // leaner syntax

  197. p1 + p2

  198. // user-defined binary operators are left-associative by default
  199. p1 - p2 - p2
  200. // same as
  201. (p1 - p2) - p2



  202. // Scala is pervasively object-oriented
  203. // *every value* is an object of some class

  204. // All basic types (Boolean, Int, Double, Unit, ...) are classes
  205. // Their elements are objects with predefined methods

  206. // Basic operators are actually all methods
  207. // E.g.

  208. val x = 4

  209. // as with user defined classes x + 2   is syntactic sugar for

  210. x.+(2)

  211. // i.e. + is a method of class Int that takes an integer
  212. // (the second operand of +) and returns its addition with
  213. // the receiving object (the first operand)

  214. // 3.2 - 1.7   is  syntactic sugar for

  215. 3.2.-(1.7)

  216. // true && false  is syntactic sugar for  

  217. true.&&(false)

  218. // x == 3   is syntactic sugar for

  219. x.==(3)


  220. // Tuples, Lists, Arrays types are also all classes

  221. val l = List(10, 11, 12)
  222. // l is an object
  223. // l ++ l   is syntactic sugar for

  224. l.++(l)


  225. //  9 :: l  is syntactic sugar for

  226. l.::(9)   

  227. // note the opposite order of the arguments
  228. // :: is a List method, not an Int method

  229. // any predefined or user-defined binary operator starting with ':'
  230. // is treated as a method of its *second* argument as above


  231. // l(1)  is syntactic sugar for

  232. l.apply(1)

  233. // head, tail, length are all parameterless methods

  234. l.head

  235. l.tail

  236. l.length


  237. // All tuple types (e.g., (Int, String) ) are classes
  238. val p = (100, "abc")

  239. // _1 and _2 are methods of the (Int, String) class

  240. p._1

  241. p._2
复制代码

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注jltj
拉您入交流群
GMT+8, 2025-12-30 20:47