scala programming ideas -- classes and objects

Object is the foundation of many modern programming languages, including scala. In object-oriented programming language

package com.test1

object Scala09_test3 {
  def main(args: Array[String]): Unit = {
    val r1 = Range(0,10)
    //For range, the number of available operations is staggering. The objects are
    //Classes and objects
    //Objects are included
    println(r1.toSeq.reverse)
    //Create a range object and print its Step value
    println(r1.step)
    val r2 = Range(0,10,3)
    println(r2.step)

    type r3=String
    val fa:r3="fa fd as fa sd fa sf"
    fa.split(" ").toSeq.foreach(print )
    //Create a string object s1 and make it sally.
    var s1:r3 ="Sally"
    var s2:r3 ="Sally"
    if(s1==s2){
      println("s1 and s2 are equals")
    }else{
      println("s1 and s2 are not equals")
    }
    //ScalaDoc scala provides
  }
}

Create class

In addition to using predefined types such as range, we can also define our own object types.

Actually,

package com.test1

object Scala09_test3 {
  def main(args: Array[String]): Unit = {
    //create some classes
    class Giraffe
    class Bear
    class Hippo
    //create some objects
    val g1 = new Giraffe
    val g2 = new Giraffe
    val b = new Bear
    val h = new Hippo
    //Each object is unique
    println(g1)
    println(g2)
    println(b)
    println(h)
    class Hyena{
      println("This is in the class body")
    }
    val hyena = new Hyena
    println(hyena)

    class Zebra{
        println("I have strips")
    }

    val zebra = new Zebra

  }
}

Methods in class

In a class, you can define the methods that belong to this class. The following bar methods belong to the dog class

package com.test1

object Scala09_test5{
  def main(args: Array[String]): Unit = {
    val cat = new Cat
    val m2 = cat.meow()
    assert("mew!"==m2,"Expeted new! got"+m2)
    //Method has special access to other elements in the class, for example, without using dots in the class
    //You can access other methods in this class.
    val hamster=new Hamster
    val e1 = hamster.exercise()
    import util.Random
   //Using multiple import imports
  /*  import util.Random
    import util.Properties

    val r = new Random
    val r2 =  Properties*/
    //Import multiple items in the same statement
  /*  import util.Random,util.Properties
    val r = new Random
    val p = Properties*/
    //Modify imported name
    //You can even import a name with love and meaning
    import util.{Random=>Bob,Properties=>Jill}
    val r = new Bob
    val p = Jill
    //You can also import all the events in the package, and you can use underline
    import util._
    //You can also use fully qualified names
    val r1 = new util.Random
    val p2 = util.Properties

    import pythagorean.RightTriangle
    val rt = new RightTriangle
    println(rt.Hypotenuse(3,4))
    println(rt.area(3,4))
  }
}

At this point, the examples use simple scripts, but eventually you are sure to write code that can be used in many places and create an object at will

package pythagorean

class RightTriangle {
  def Hypotenuse(a:Double,b:Double):Double={
    Math.sqrt(a*a+b*b)
  }

  def area(a:Double,b:Double):Double={
    a*b/2
  }
}

test

Robust code must be tested constantly, that is, after every change. Some part of the code may accidentally affect other code, and pass the test,

The automatic tdd method needs to be looked at later.

 

Domain: a domain is a var or val that forms part of an object, and each diagonal gets its own storage for its domain

package com.test1

object Scala09_test6{
  def main(args: Array[String]): Unit = {
  //test
    //The code of Jianzhuang must be tested continuously, that is, it needs to be tested after each modification
    //In order to make the source code easy to test, we have created our own micro test system. The goal is to provide a minimization method with the following characteristics
    //Write the expected result next to the right test of the expression, which is easier to understand with code
    import java.util.logging._
    trait Logging{
      val log = Logger.getLogger(".")
    }

   /* class Cup{
      var percentFull = 50
    }

    val c1 = new Cup
    c1.percentFull=100

    println(c1.percentFull)
    val c2 = new Cup
    println(c2.percentFull)*/
    
    class Cups{
      var  percentFull = 0 
      val max = 100
      def add(Increase:Int):Int={
        percentFull += Increase
        if(percentFull > max){
          percentFull = max 
        }
        percentFull
      }
    }
    

  }
}

for cycle

The for loop traverses a sequence of values, using each of them to perform certain operations. The for loop begins with the keyword for,

package com.test1

object Scala09_test6{
  def main(args: Array[String]): Unit = {
  //test
    //The code of Jianzhuang must be tested continuously, that is, it needs to be tested after each modification
    //In order to make the source code easy to test, we have created our own micro test system. The goal is to provide a minimization method with the following characteristics
    //Write the expected result next to the right test of the expression, which is easier to understand with code
    import java.util.logging._
    trait Logging{
      val log = Logger.getLogger(".")
    }

   /* class Cup{
      var percentFull = 50
    }

    val c1 = new Cup
    c1.percentFull=100

    println(c1.percentFull)
    val c2 = new Cup
    println(c2.percentFull)*/

    class Cups{
      var  percentFull = 0
      val max = 100
      def add(Increase:Int):Int={
        percentFull += Increase
        if(percentFull > max){
          percentFull = max
        }
        percentFull
      }
    }
    var result=""
    for(i<-0 to 10){
      result += i+" "
    }
    println(result)

    result = ""
    for(i <- 0 until 10 ){
      result+=i+" "
    }
    println(result)

    result = ""
    for(i <- Range(0,10) ){
      result+=i+" "
    }
    println(result)

    result = ""
    for(i <- Range(0,10,2) ){
      result+=i+" "
    }
    println(result)

    //Add a row
    println(Range(0,10).inclusive)

    //If in red
    for(i<- 1 to 10;if(i%2 == 0 )){println(i)}
    for(i<- 1 to 10;if(i%2 == 0 )){println(i)}

    //Vector
    //A Vector is a container, an object that holds other objects, also known as a collection
    //Vertor is part of the standard scala package, so no one needs to use it
    println("========================================")
    val v1 = Vector(1,3,5,6,11,13)
    println(v1(4))
    println("========================================")
    var  result1 = ""
    for(i <- v1){
      result1 += i+ " "
    }
    println(result1)

    val v3 = Vector(1.1,2.2,3.3,4.4)
    println(v3.reverse)
    val v4 = Vector("Twas","Brilling","And","Slithy","Toves")
    println(v4.sorted)
    println(v4.head)
    println(v4.tail(2 ))
    //There are some unusual places where all Vector objects are created without the new keyword. For convenience
    //scala allow
    var v5:Vector[String]=Vector("Twas","Brilling","And","Slithy","Toves")
    var v6=Vector(1,"111",2,22.22,333)
    for(i <- Range('a','z').inclusive.reverse){
      print( i.toChar )
    }
    var interVector:Vector[Int] = Vector(1,2,3,4,5,6,7,8,9)
    var doubleVector:Vector[Double] = Vector(1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9)
    println("interVector.sum: "+interVector.sum)
    println("interVector.min: "+interVector.min)
    println("interVector.max: "+interVector.max)
    println("========================================")
    println("doubleVector.sum: "+doubleVector.sum)
    println("doubleVector.min: "+doubleVector.min)
    println("doubleVector.max: "+doubleVector.max)

    val stringVector:Vector[String]=Vector("iit1","iit2","iit3","iit4","iit5","iit6","iit7","iit8")
    println("========================================")
    //println("stringVector.sum: "+stringVector.sum)
    println("stringVector.min: "+stringVector.min)
    println("stringVector.max: "+stringVector.max)

    println(Range(1,100).toVector.sum)
    println(Range(1,100).sum)

    var myVector1:Vector[Int]=Vector(1,1,2,3,4,565,7)
    var myVector2:Vector[Int]=Vector(1,1,2,3,4,565,7)
    println(myVector1 == myVector2)
    println(Set(1,2,2,3,4,5,6,7,8,88))
    println(List(1,1,1,1,2,2,3,4,5,6,7,8,88))
  }
}

More conditional expressions

package com.test1

object Scala09_test7{
  def main(args: Array[String]): Unit = {
  //More conditional expressions
    //Let's practice creating methods and writing methods that accept boolean type parameters
    def trueOrFalse(exp:Boolean):String={
      if(exp){
        "It's true"
      }else{
        "It's false"
      }
    }

    val b = 1
    println(trueOrFalse(b<3))
    println(trueOrFalse(b>0))

    val v = Vector(1)
    val v2 = Vector(3,4)
    println(trueOrFalse(v == v.reverse))
    println(trueOrFalse(v2 == v2.reverse))

    def checkTruth(exp1:Boolean,exp2:Boolean):String={
      if(exp1 && exp2){
        "Both are true"
      }else if(!exp1 && !exp2){
        "Both are false"
      }else if(exp1){
        "First:True ,second:false"
      }else{
        "First:True ,second:true"
      }
    }

    println(checkTruth(true||false,true))
    println(checkTruth(false||false,true))
    println(checkTruth(true ,false))
    println(checkTruth(false,true))

  }
}

 

117 original articles published, praised 27, visited 310000+
Private letter follow

Tags: Scala Programming Java

Posted on Sat, 01 Feb 2020 07:48:39 -0800 by digitalflash