[英]Scala: make an implicit class accessible from classes injecting the class defining it
[英]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
標識符 可以影響隱含的內容包括val
, def
, object
和case class
的生成的伴隨對象。 簡單的class
和type
s不會創建標識符,因此不會影響導入的implicit
標識符。
implicit class Password
只是class Password
和implicit 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.