Scala 槽点 - require

require

def this(name: String, age: Int) = {
  this()
  require(name != null && !name.isEmpty, "name")
  require(age > 0, "illegal age")
  Preconditions.checkArgument(name != null && !name.isEmpty, "name required")  // 使用 guava 工具类,这行编译不过... 改写为下两种调用方式可通过
// Preconditions.checkArgument(name != null && !name.isEmpty, "name required".asInstanceOf[Any])  
// Preconditions.checkArgument(name != null && !name.isEmpty, "name required", null)
  setAge(age)
  setName(name)
}

什么鬼

  1. require

    • 函数签名: final def require(requirement: Boolean, message: => Any) ,注意第二个参数类型是一个函数
    • 以上栗子中调用了两次 require 函数,生成两个匿名对象...
  2. ambiguous reference to overloaded definition

    • 编译错误信息:
      Error:(44, 21) ambiguous reference to overloaded definition,
      both method checkArgument in object Preconditions of type (x$1: Boolean, x$2: String, x$3: Object*)Unit
      and  method checkArgument in object Preconditions of type (x$1: Boolean, x$2: Any)Unit
      match argument types (Boolean,String)
            Preconditions.checkArgument(name != null && !name.isEmpty, "name required")
      
posted @ 2019-10-10 17:26  邓晓锋  阅读(859)  评论(0编辑  收藏  举报