fichier Equal.scala

trait Equal {
  def isEqual(x: Any): Boolean
  def isNotEqual(x: Any): Boolean = !isEqual(x)

}

fichier Point.scala:

class Point(xc:Int,yc:Int) extends Equal{

  var x: Int = xc
  var y: Int = yc

  def move(dx: Int, dy: Int) {
    x = x + dx
    y = y + dy
    println ("x abscisse: " + x)
    println ("y ordonnee: " + y)
  }

  def isEqual(obj: Any) =
    obj.isInstanceOf[Point] && obj.asInstanceOf[Point].x == x
}

fichier Location.scala

class Location( val xc: Int, val yc: Int, val zc: Int) extends Point(xc, yc) {
  var z: Int = zc
  def move(dx: Int, dy: Int, dz: Int) {
    x = x + dx
    y = y + dy
    z = z + dz
    println("Point x location : " + x);
    println("Point y location : " + y);
    println("Point z location : " + z);
  }
}

fichier Main.scala

object Main extends App  {

  val loc = new Location(10, 20, 15)

  // Move to a new location
  loc.move(10, 10, 5);

  val p1 = new Point(2, 3)
  val p2 = new Point(2, 4)
  val p3 = new Point(3, 3)

  println(p1.isNotEqual(p2))
  println(p1.isNotEqual(p3))

  def matchTest(x: Int): String = x match {
    case 1 => "one"
    case 2 => "two"
    case _ => "many"
  }
  println(matchTest(1))
  println(matchTest(4))

  def matchTest2(x: Any): Any = x match {
    case 1 => "one"
    case "two" => 2
    case y: Int => "scala.Int"
    case _ => "many"
  }

  println(matchTest2("two"))
  println(matchTest2("test"))
  println(matchTest2(1))
  println(matchTest2(6))
}

exemple 2:

class Person {
  var name = ""
  override def toString = getClass.getName + "[name=" + name + "]"
}

class Employee extends Person {
  var salary = 0.0
  override def toString = super.toString + "[salary=" + salary + "]"
}


object TestEmploye extends App  {
  val fred = new Employee
  fred.name = "Fred"
  fred.salary = 50000
  println(fred)

  val alice = new Person("Alice", 25)
  val bob = new Person("Bob", 32)
  val charlie = new Person("Charlie", 32)

  for (person <- List(alice, bob, charlie)) {
    person match {
      case Person("Alice", 25) => println("Hi Alice!")
      case Person("Bob", 32) => println("Hi Bob!")
      case Person(name, age) =>
        println("Age: " + age + " year, name: " + name + "?")
    }
  }

  case class Person(name: String, age: Int)

}

Retour à l'accueil