scala教程:Unit、Null、Nothing、Nil数据类型

Unit

Unit 是数据类型,就像 Int、String 一样,是个类型

Unit 只有一个值: ()。就像 100 是 Int 类型的值,3.14 是 Double 类型的值

Unit是anyval的子类型

应用场景

相当于 JAVA中的 void ,用来声明 函数 或 方法 的返回值,表示 没有返回值

就是说:即使 用 Unit 声明 方法、函数,但实际上还是有 返回值,即:()

原因: scala 是 函数式 语言,所以要有返回值,没有则返回 ()

例子

object Test {
  def main(args: Array[String]): Unit = {
    def testUnit(): Unit = {
      println("Hello 测试")
    }
    testUnit()
  }
}

例子:返回值

object Test {
  def main(args: Array[String]): Unit = {
    def testUnit(): Unit = {
      println("Hello 测试")
    }
    val res=testUnit()
    println(res)
  }
}

Null

Null 是数据类型,就像 Int、String 一样,是个类型

Null 只有一个值: null,表示 空引用。就像 100 是 Int 类型的值,3.14 是 Double 类型的值

应用场景

null 可以赋值给任意 引用类型(AnyRef)

但是 不能赋值给 值类型 (AnyVal: Int, Float, Char, Boolean, Long, Double, Byte, Short)

尽量少用

例子

Int是值类型,把 null 赋值给 Int,会报错

object Test {
  def main(args: Array[String]): Unit = {
    val i:Int=null // idea可能不报错,但运行报错
    val s : String = null // 可运行
  }
}

Nothing

Nothing 是数据类型,就像 Int、String 一样,是个类型

Nothing 没有值。就像 100 是 Int 类型的值,3.14 是 Double 类型的值,但是 Nothing 没有值

Nothing是 所有类型的子类,也是 null 的子类,但是可以定义类型

Nothing不好理解,在java中没有对应的类型

应用场景

函数抛出异常,那返回值类型就是 Nothing

如:Breaks 类的 break() 方法源代码,如下:

def break(): Nothing = { throw breakException }

例子

object Test2 {
  def main(args: Array[String]): Unit = {
    def chufa(a:Int,b:Int):Int = {
      if(b==0){
        throw new RuntimeException("b不能是0")
      }else{
        return a/b
      }
    }
    val res = chufa(4,0)
    println(res)
  }
}

抛出异常的语句: throw new RuntimeException("b不能是0") 就返回 Nothing ,但获取不到值

Nil

Nil 是一个 空的 List,定义为 List[Nothing]

空 Iterator:Nil.iterator


原文出处:/show_1IX19WeWOPVW.html