【问题标题】:Implicit class method not found未找到隐式类方法
【发布时间】:2019-02-12 07:47:58
【问题描述】:

我有一个带有隐式类的对象:

object ModelUtils {
  implicit class RichString(str: String) {
    def isNullOrEmpty(x: String): Boolean = x == null || x.trim.isEmpty
  }
}

但是,当我尝试使用它时,IntelliJ 找不到 isNullOrEmpty 方法:

"TestString".isNullOrEmpty

我尝试了各种导入来导入该方法,但均无济于事。我错过了什么?

【问题讨论】:

    标签: scala implicit


    【解决方案1】:

    问题可能不在于导入本身,而在于不必要的参数x。如果你想在没有任何参数的情况下调用.isNullOrEmpty,那么你必须使用str,而不是x

    object ModelUtils {
      implicit class RichString(str: String) {
        def isNullOrEmpty: Boolean = str == null || str.trim.isEmpty
      }
    }
    
    import ModelUtils._
    
    println("TestString".isNullOrEmpty)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-06
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      相关资源
      最近更新 更多