Usages of Null / Nothing / Unit in Scala

后端 未结 8 1708
刺人心
刺人心 2020-11-30 18:34

I\'ve just read: http://oldfashionedsoftware.com/2008/08/20/a-post-about-nothing/

As far as I understand, Null is a trait and its only instance is

相关标签:
8条回答
  • 2020-11-30 19:26

    Nothing is often used implicitly. In the code below, val b: Boolean = if (1 > 2) false else throw new RuntimeException("error") the else clause is of type Nothing, which is a subclass of Boolean (as well as any other AnyVal). Thus, the whole assignment is valid to the compiler, although the else clause does not really return anything.

    0 讨论(0)
  • 2020-11-30 19:28

    Do you have usages of Unit / Null / Nothing as something else than a return type?


    Unit can be used like this:

    def execute(code: => Unit):Unit = {
      // do something before
      code
      // do something after
    }
    

    This allows you to pass in an arbitrary block of code to be executed.


    Null might be used as a bottom type for any value that is nullable. An example is this:

    implicit def zeroNull[B >: Null] =
        new Zero[B] { def apply = null }
    

    Nothing is used in the definition of None

    object None extends Option[Nothing]
    

    This allows you to assign a None to any type of Option because Nothing 'extends' everything.

    val x:Option[String] = None
    
    0 讨论(0)
提交回复
热议问题