簡體   English   中英

對象中無法訪問Scala隱式類成員

[英]Scala Implicit class member is not accessible in object

我使用Scala bCrypt 包裝器來加密用戶密碼,這個包裝器提供了一個隱式類。

package object bcrypt {

  implicit class Password(val pswrd: String) extends AnyVal {
    def bcrypt: String = B.hashpw(pswrd, BCrypt.gensalt())

    def bcrypt(rounds: Int): String = B.hashpw(pswrd, BCrypt.gensalt(rounds))

    def bcrypt(salt: String): String = B.hashpw(pswrd, salt)

    def isBcrypted(hash: String): Boolean = B.checkpw(pswrd, hash)
  }

  def generateSalt: String = B.gensalt()
}

但是我面臨一個奇怪的問題,每當我在課堂上使用這個隱式會話時它工作得很好但是融合並不適用於對象案例類

scala> import com.github.t3hnar.bcrypt._
import com.github.t3hnar.bcrypt._

scala> class Password(secret: String) {
     |   def validate(userSecret: String): Boolean = userSecret.isBcrypted(secret)
     | 
     |   override def toString = secret
     | }
defined class Password

scala> object Password {
     |   def apply(secret: String): Password = new Password(secret)
     | 
     |   def getEncrypted(secret: String) = new Password(secret.bcrypt)
     | }
<console>:18: error: value bcrypt is not a member of String
         def getEncrypted(secret: String) = new Password(secret.bcrypt)
                                                                ^

scala> 

我不確定我在這里做錯了什么。

任何穩定標識符都會導入implicit標識符 可以影響隱含的內容包括valdefobjectcase class的生成的伴隨對象。 簡單的classtype s不會創建標識符,因此不會影響導入的implicit標識符。

implicit class Password只是class Passwordimplicit def Password語法糖,因此代碼中名為Password的標識符將implicit def

所以雖然這段代碼編譯好了:

object Foo {
  import bcrypt._
  class Password()
  "123".bcrypt
}

以下所有代碼段都將無法編譯:

object Foo2 {
  import bcrypt._
  val Password = 1
  "123".bcrypt
}

object Foo3 {
  import bcrypt._
  def Password() = 1
  "123".bcrypt
}

object Foo4 {
  import bcrypt._
  case class Password()
  "123".bcrypt
}

object Foo5 {
  import bcrypt._
  object Password
  "123".bcrypt
}

您的案例中的解決方案很簡單:將隱式類重命名為其他類,這不太可能與其他標識符沖突。 例如, implicit class PasswordExtensions

如果您無法重命名原始代碼中的implicit class ,則可以使用其他名稱導入它: import com.github.t3hnar.bcrypt.{Password => PasswordExtensions, _}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM