Scala - simple design by contract

I am learning Scala as a personal project, as I am fed up with the verbosity of Java. I like a lot of what I see, but I wonder if there is a way to effectively implement some simple method contracts. I am not (required) after a full DbC, but there is a way: -

  • indicate that the parameter or field of the class is REQUIRED, i.e. CANNOT be null. The Option option seems clean if an OPTIONAL value is present, but I want to specify class invariants (x is required), and also briefly indicate that the parameter is required. I know what I can do if by throwing an exception, but I want the language to be a VERY common use case for this. I really like my interfaces, I don’t like defensive programming.

  • Is it possible to define compressed and efficient types (runtime performance), such as "NonNegativeInt" - I want to say that parameter> = 0. Or within the range. PASCAL had these types, and I found them great for communication. This is one of the big drawbacks of C, C ++, Java, etc. When I say concise , I want to say that I want to declare a variable of this type as easily as a regular int, without having to create new ones and each instance on the heap.

+5
source share
2 answers

(1), Option . , scala , Java. scala , ( scala ). idiomatic scala, Option, , .

( , ) NotNull. . NotNull 2.8 - ?

(2) scala 2.10 . , Int . , , - Int NonNegativeInt ( , int ). , , NonNegativeInt, , , . ( ), , .

UPDATE. NonNegativeInt ( UInt):

object UInt {
  def apply( i: Int ): UInt = {
    require( i >= 0 )
    new UInt( i )
  }
}
class UInt private ( val i: Int ) extends AnyVal {
  override def toString = i.toString
  def +( other: UInt ) = UInt( i + other.i)
  def -( other: UInt ) = UInt( i - other.i)
  def *( other: UInt ) = UInt( i * other.i)
  def /( other: UInt ) = UInt( i / other.i)
  def <( other: UInt ) = i < other.i
  // ... and so on
}

REPL:

scala> UInt(123)
res40: UInt = 123

scala> UInt(123) * UInt(2)
res41: UInt = 246

scala> UInt(5) - UInt(8)
java.lang.IllegalArgumentException: requirement failed
        at scala.Predef$.require(Predef.scala:221)
        at UInt$.apply(<console>:15)
        ...
+7

null, ?

, bar null , , . , Option.

, . null, . Either ScalaZ Validation.

( , ), . Spire Natural. , , , .

Option Scala Option factroy. :

scala>     val s1 = "Stringy goodness"
s1: String = Stringy goodness

scala>     val s2: String = null
s2: String = null

scala>     val os1 = Option(s1)
os1: Option[String] = Some(Stringy goodness)

scala>     val os2 = Option(s2)
os2: Option[String] = None
+4

All Articles