簡體   English   中英

Scala隱式轉換apply方法

[英]Scala implicit conversion of apply method

我嘗試了以下代碼在代碼中創建選項檢查樣式:

object Test {
  trait Check
  object x extends Check
  def option() = false
  def option(xx: Check) = true
  implicit class AugmentCheck(s: String) {
    def apply() = ""
    def apply(xx: Check) = s
  }
}
import Test._

val delete = option ( x )
val force  = option (   )

val res = "mystring" (   )

但是我面臨以下問題:

<console>:11: error: type mismatch;
 found   : String("mystring")
 required: ?{def apply: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method augmentString in object Predef of type (x: String)scala.collection.
immutable.StringOps
 and method AugmentCheck in object Test of type (s: String)Test.AugmentCheck
 are possible conversion functions from String("mystring") to ?{def apply: ?}
           val res = "mystring" (   )
                     ^
<console>:11: error: String("mystring") does not take parameters
           val res = "mystring" (   )

這很不幸,因為即使符號名稱存在歧義,函數簽名也不應該有任何歧義。

如果我引入方法“apply”,當有參數時它可以正常工作,但不是沒有:

           val res = "mystring" apply ( x )

           res == ""

在這種情況下,如何刪除關鍵字“apply”?

而不是用x或表示開啟關閉狀態   那么使用y表示n表示

object Test {
  val y = true
  val n = false
  class DefaultConfigValue[U](val v: U)
  implicit class ConfigValue[U](v: U) {
    def y = v
    def n(implicit default: DefaultConfigValue[U]) = default.v
  }
  implicit val defaultConfigString = new DefaultConfigValue("")
}

import Test._
import language.postfixOps

val delete = y
val force  = n

val res1 = "my first string"   y
val res2 = "my second string"  n

請注意如何導入postfixOps ,然后只需添加額外的空格即可將字符串配置選項的所有yn s對齊到同一列中。

我不確定這是否有意義,但我寫了上面的代碼,你應該能夠使用任何類型(不僅僅是字符串)與yn后綴運算符的選項。 要啟用新類型,您只需為該類型創建一個隱式DefaultConfigValue ,以便no選項可以返回。

我強烈建議不要使用這種模式,因為它違反了最少驚喜的原則。

StringOps已經在String上定義了apply(n)以返回第N個字符,任何其他重載都會讓很多人感到困惑。 即使在DSL的背景下。

Option也是一個易於理解的術語,其含義在這里重載。

最后: x非常常用作方法的參數和模式匹配中的綁定值。 在這樣的廣泛范圍內使用它會導致很多陰影,並且可能會導致一些非常意外的錯誤消息。

您能否更好地了解您想要實現的目標,以便我們能夠提出更好的選擇?

暫無
暫無

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

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