case classes and simple pattern matching

Posted by aveic 3 years ago

After working for some time with Scala I've realised that I extremely lack having `case` classes (https://docs.scala-lang.org/tour/case-classes.html) and pattern matching in PHP: You can write some example code: ```php // you define a case class case class WithdrawalPolicy(float $fee, bool $daily) // instances of case classes are immutable objects that are compared by state { // ... probably other methods (but usually they don't have any though) } // which is equivalent to class WithdrawalPolicy { immutable protected $feeRate; /* @var float $feeRate */ immutable protected $daily; /* @var bool $daily */ public function __construct(float $feeRate, bool $daily) { $this->_feeRate = $feeRate; $this->_daily = $daily; } // some magic methods for accessing $feeRate, $daily // also we get == and != operators for free that compare the state } // following creation and usage: $policy = WithdrawalPolicy($feeRate=0.12, $daily=true); echo $policy->feeRate; echo $policy->daily; // and the best part is pattern matching $fee = $policy match { case WithdrawalPolicy(_, true) => 0.0023; // do smth with daily policies case WithdrawalPolicy(rate, _) => rate * 0.98; // whether daily or not, do smth with feeRate } ``` They come in handy in projects with a lot of DTOs, ValueObjects and innerDSL concepts.