Advertisement
ZivkicaI

Lista i metodi

Nov 27th, 2019
559
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.80 KB | None | 0 0
  1. package exercises.part2oop
  2.  
  3. abstract class MyList {
  4.  
  5.   def head: Int
  6.   def tail: MyList
  7.   def isEmpty: Boolean
  8.   def add(element :Int): MyList  //zatoa shto e immutable nema new
  9.  
  10. }
  11. object Empty extends MyList{
  12.  
  13.   def head: Int = throw new NoSuchElementException
  14.   def tail: MyList = throw new NoSuchElementException
  15.   def isEmpty: Boolean = true
  16.   def add(element :Int): MyList = new Cons(element,  Empty)
  17.  
  18. }
  19. class Cons(h:Int, t:MyList) extends MyList{
  20.   def head: Int = h
  21.   def tail: MyList = t
  22.   def isEmpty: Boolean = false //at least one element
  23.   def add(element :Int): MyList = new Cons(element, this)
  24.  
  25. }
  26.  
  27. object ListTest extends App{
  28.   //val list =new Cons(1,Empty)
  29.   val list = new Cons(1,new Cons(2, new Cons(3, Empty)))
  30.   println(list.tail.head)
  31.   println(list.add(4).head)
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement