Advertisement
Sylv3rWolf

Untitled

Dec 10th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.09 KB | None | 0 0
  1. object HelloWorld {
  2.    def main(args: Array[String]) {
  3.       println("Hello, world!")
  4.       val euro = new Euro(10,20) with Ordered[Euro]
  5.       val euro2 = new Euro(5,1) with Ordered[Euro]
  6.       println("Euro dodaj" ,euro+euro2)
  7.       println("Euro odejmij", euro2-euro)
  8.       println("Euro: ",euro)
  9.       println("Euro 2x: ",euro*2)
  10.       println(euro < euro2)
  11.       println(euro >= euro2)
  12.      
  13.    }
  14.    
  15. abstract class Currency(val symbol:String) {
  16.     override def toString(): String = symbol
  17. }
  18.  
  19. class Euro(val euro:Int, val cents:Int = 0) extends Currency("EUR ") with Ordered[Euro] {
  20.     val inCents = euro*100+cents
  21.     def +(x:Euro):Euro = {
  22.       val noweEuro = x.euro+euro
  23.       val noweCenty = x.cents+cents
  24.       return new Euro(noweEuro,noweCenty)
  25.     }
  26.     def -(x:Euro):Euro = {
  27.       val noweEuro = x.euro-euro
  28.       val noweCenty = x.cents-cents
  29.       return new Euro(noweEuro,noweCenty)
  30.     }
  31.     def *(x:Int):Euro = {
  32.       var noweEuro = x*euro
  33.       var noweCenty = x*cents
  34.       if(noweCenty>99) {
  35.           noweEuro = noweEuro + noweCenty/100
  36.           noweCenty = noweCenty - noweCenty/noweEuro
  37.       }
  38.       return new Euro(noweEuro,noweCenty)
  39.     }
  40.     println("Euro",euro)
  41.     println("Centy",cents)
  42.     println("InCents",inCents)
  43.    
  44.     override def toString(): String = {
  45.         if(cents>0) {
  46.             return super.toString+euro+"."+cents
  47.         }
  48.         else {
  49.             return super.toString+euro+".--"
  50.         }
  51.     }
  52.    
  53.     def compare(other: Euro) = {
  54.         this.euro - other.euro
  55.         this.cents - other.cents
  56.     }
  57. }
  58.  
  59. object Euro {
  60.     def fromCents(inCents: Int):Euro = { return new Euro(0,inCents)
  61.   }
  62. }
  63.  
  64. trait Ordered[A] {
  65.     def compare(that: A) : Int
  66.     def < (that: A) : Boolean = (this compare that) < 0
  67.     def > (that: A) : Boolean = (this compare that) > 0
  68.     def <= (that: A) : Boolean = (this compare that) <= 0
  69.     def >= (that: A) : Boolean = (this compare that) >= 0
  70.    
  71. }
  72.  
  73. case class EmailAddress(address: String)
  74. case class Person(name: String, age: Int, emailAddresses: List[EmailAddress])
  75.  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement