How to set a test to match the pattern

I am new to scala but basically found my way ...

Here I ask for a recommended / best practice / idiomatic way to implement this:

  • internally, MyClass uses a state type that is implemented using a sealed case class hierarchy
  • but in the API, only some logical predicate should be opened, which is implemented by matching with the (internal) state.

My implementation is currently running line by line ...

def isSane: Boolean = state match {
    case Ok(_,'valid) => true
    case _            => false
}

But this decision seems awkward to me, as if expressing something in three lines of code, which has only information content, standing on one line of code. In fact, I would like to write:

def isSane: boolean = state matches Ok(_, 'valid)

/, scala, , , . , ?

+3
3

, ?

trait State { def sane: Boolean }

trait InvalidState extends State { def sane = false }

case class Ok(whatever: Whatever, s: Symbol) extends State {
   def sane = { s == 'valid }
}

case class Failure(msg: String) extends InvalidState 

case class WarmingUp extends InvalidState

// ...

def isSane(): Boolean = state.sane

, - , Daniel:

class Matcher[T](o: T) {
   def matches(pf: PartialFunction[T, Unit]) = pf isDefinedAt o
}

object Matcher {
   implicit def o2matcher[T](o: T): Matcher[T] = new Matcher(o)
}

// then
def isSane = state matches { case Ok(_,'valid) => }
+2

- :

abstract class State {
  def matches(pf: PartialFunction[State, Unit]) = pf isDefinedAt this
}

// then

def isSane = state matches { case Ok(_,'valid) => }

matches , case, . , Unit. , matches isDefinedAt, , case, .

+2

Symbol state:

def isSane: Boolean =
  state.secondSymbolPropertyWhateverItsCalled == 'valid

, state Ok, :

def isSane: Boolean =
  state.isInstanceOf[Ok] && state.asInstanceOf[Ok].symbolProp == 'valid

, .

, isSane :

def isSane: Boolean =
  state.isSane
+1

Source: https://habr.com/ru/post/1764252/


All Articles