Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Scala
Posted by: Pahay Ragh
Added: Oct 25, 2020 6:00 PM
Views: 9
Tags: no tags
  1. package rtrscalarefreshconcepts
  2.  
  3. object ScalaTypeBounds extends App{
  4.  
  5.   trait Thing
  6.   trait Vehicle extends Thing
  7.   class Car extends Vehicle
  8.   class Jeep extends Car
  9.   class Coupe extends Car
  10.   class Motorcycle extends Vehicle
  11.   class Vegetable
  12.  
  13.   class Parking[A](val place: A)
  14.  
  15.   val parkingVehicle:Parking[Vehicle] = new Parking(new Jeep)
  16.   val parkingCar:Parking[Car] = new Parking(new Jeep)
  17.   val parkingJeep:Parking[Jeep] = new Parking(new Jeep)
  18.   val parkingMotorCycle:Parking[Vehicle] = new Parking(new Motorcycle)
  19.   val parkingVegtable = new Parking(new Vegetable)
  20.  
  21.   // we can create type parameter restrictions
  22.   // To create them, we make use of Scala type bounds.
  23.  
  24.   //Upper Type Bounds < subtype
  25.   class ParkingTypeBound[A <: Vehicle](val place:A)
  26.  
  27.   val parkJeep:ParkingTypeBound[Vehicle] = new ParkingTypeBound(new Jeep)
  28.  
  29.  //Lower Type Bounds > supertypes Jeep Included
  30.   class ParkingLowerJeep[A >: Jeep ](val place:A)
  31.   class Wrangler extends Jeep
  32.  
  33.   val parkWrangler = new ParkingLowerJeep(new Wrangler)
  34.  
  35.   // Vegatable can be Parked as its anyref anf super type of jeep
  36.   val parkVeg = new ParkingLowerJeep(new Vegetable)
  37.  
  38.   class ParkingUpperLower[A >:Jeep <:Vehicle](val place:A)
  39.   val parkWrangVehicle = new ParkingUpperLower(new Wrangler)
  40. //  val parkVegUPLOw = new ParkingUpperLower(new Vegetable)   //Wotn Work as its not subtype of Vehicle
  41. }
  42.