Advertisement
Guest User

Scala Stuff

a guest
Nov 27th, 2014
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.48 KB | None | 0 0
  1. case class Person(name: String)
  2.  
  3. case class Cat(name: String, color: String, favoriteFood:String){
  4.     def eat(food:String) : String = {
  5.         if (food==favoriteFood) "OMNOMNOM" else "Bleeeh"
  6.     }
  7.  
  8.     def greet(person: Person): String = {
  9.         person match {
  10.             case Person("Noel") => "Hi"
  11.             case Person(first)  => s"Goodbye ${first}"
  12.             case _              => "No"
  13.         }
  14.     }
  15. }
  16.  
  17. object ChipShop {
  18.     def serves(cat : Cat) : Boolean = {
  19.         cat match {
  20.             case Cat(_, _, "Chips") => true
  21.             case _                  => false
  22.         }
  23.     }
  24. }
  25.  
  26.  
  27.  
  28. val oswald    = Cat("Oswald", "Black", "Milk")
  29. val henderson = Cat("Henderson", "Ginger and White", "Chips")
  30. val quentin   = Cat("Quentin", "Tabby and White", "Curry")
  31.  
  32. val noel = Person("Noel")
  33. val joel = Person("Joel")
  34.  
  35. trait Visitor {
  36.     def id: String
  37. }
  38. //Algebraic Data Types, ANDing and ORing to make types
  39. case class Anon(id: String) extends Visitor
  40. case class User(id: String) extends Visitor
  41.  
  42. trait Shape {
  43.     def width: Int
  44.     def height: Int
  45.     def area : Double = this match {
  46.         case Rectangle(width, height) => width*height
  47.         case Circle(radius)           => Math.pow(radius, 2) * Math.PI
  48.     }
  49. }
  50.  
  51. case class Rectangle(width: Int, height: Int) extends Shape {
  52.  
  53. }
  54.  
  55. case class Circle(radius : Int) extends Shape {
  56.     def width : Int = {
  57.         radius * 2
  58.     }
  59.  
  60.     def height : Int = {
  61.         radius * 2
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement