(स्काला 2.11.8)स्काला निहित संकल्प typeclasses
निम्नलिखित कोड पर विचार करें:
- क्यों नहीं करता है ': मैं कोड के इस टुकड़े के बारे में सवाल का एक समूह है
object ScalaTest extends App { class Wrapper { import Wrapper._ def init(): Unit = { // "could not find implicit value for parameter tc: ScalaTest.Wrapper.TC[Int]" printWithTC(123) // Compiles printWithTC(123)(IntTC) // Compiles again! printWithTC(132) } } object Wrapper { trait TC[A] { def text(a: A): String } implicit object IntTC extends TC[Int] { override def text(a: Int) = s"int($a)" } def printWithTC[A](a: A)(implicit tc: TC[A]): Unit = { println(tc.text(a)) } } (new Wrapper).init() }
टी
IntTC
पहली जगह में हल हो गया है? - यह एक बार उपयोग किए जाने के बाद क्यों संकलित करता है? (यदि आप पहले आमंत्रण पर टिप्पणी करते हैं, कोड काम करता है)
- टाइपक्लास इम्प्लिकेट्स को ठीक से हल करने के लिए कहां रखा जाना चाहिए?
मुझे नहीं पता कि क्या हो रहा है, लेकिन सिर्फ ध्यान दिया गया है कि यदि आप ऑब्जेक्ट को कक्षा से पहले ले जाते हैं, तो कोड भी संकलित करता है। – Dima