簡體   English   中英

為什么scope中沒有任何方法、成員或object與隱式class同名

[英]Why can there not be any method, member or object in scope with the same name as the implicit class

scope 中可能沒有與隱式 class 同名的任何方法、成員或 object。

https://docs.scala-lang.org/overviews/core/implicit-classes.html

只是想知道為什么會這樣? 我知道普通類可以有伴生對象,為什么不是隱含對象? 是不是和這里的原因一樣

scope 中可能沒有與隱式 class 同名的任何方法、成員或 object。

只是想知道為什么會這樣?

簡短的回答是:因為它們方法!

稍長一點的答案是:因為隱式類是 class 和方法的語法糖。

記住我們在有隱式類之前曾經寫過的東西:

final class IntFactorialExtension(n: Int) {
  final def ! = (1 to n) reduce (_ * _)
}

implicit def intFactorialExtension(n: Int) = new IntFactorialExtension(n)

5! //=> 120: Int

斯卡斯蒂鏈接

正如SIP-13 –隱式類(從您引用的文檔鏈接)中定義的那樣,隱式 class 只是方法(隱式轉換)和 class 的語法糖,就像我們以前在隱式類之前手寫一樣 [粗體強調我的]:

隱式 class必須在允許方法定義的 scope 中定義(不在頂層)。 隱式 class 被脫糖為 class 和隱式方法配對,其中隱式方法模仿 class 的構造函數。

生成的隱式方法將與隱式 class 具有相同的名稱 這允許使用 class 的名稱導入隱式轉換,正如人們對其他隱式定義所期望的那樣。 例如,表單的定義:

 implicit class RichInt(n: Int) extends Ordered[Int] { def min(m: Int): Int = if (n <= m) n else m... }

將由編譯器轉換如下:

 class RichInt(n: Int) extends Ordered[Int] { def min(m: Int): Int = if (n <= m) n else m... } implicit final def RichInt(n: Int): RichInt = new RichInt(n)

So, because an implicit class desugars into both a name in the type realm (a class) and a name in the value realm (a method / implicit conversion), it must be legal and valid in both the type realm and the value realm,這對於隱式轉換特別意味着 scope 中的值 realm 中不能有另一個名稱。

可能存在潛在的名稱沖突,因為

implicit class fooOps(v: TypeWeWantToAddExtensionTo) extends AnyVal {
  def extensionMethod1() = ???
}

val v: TypeWeWantToAddExtensionTo = ???
v.extensionMethod1()

擴展到

fooOps(v).extensionMethod1()

因此,如果 scope 中有另一個fooOps定義,則可能會導致名稱沖突。

從 Scala 3 開始,這不再是問題,因為我們不必為隱含的 class 命名,而是只寫

extension (v: TypeWeWantToAddExtensionTo) 
  def extensionMethod1() = ???
  def extensionMethod2() = ???
  ...

暫無
暫無

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

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