SORU
4 EKİM 2010, PAZARTESİ


Scala tanımlayıcı "örtük" ne?

Bir fonksiyon implicitly adlı Scala örneklerde kullanılan gördüm. Ve nasıl kullanılır?

Example here:

scala> sealed trait Foo[T] { def apply(list : List[T]) : Unit }; object Foo {
     |                         implicit def stringImpl = new Foo[String] {
     |                             def apply(list : List[String]) = println("String")
     |                         }
     |                         implicit def intImpl = new Foo[Int] {
     |                             def apply(list : List[Int]) =  println("Int")
     |                         }
     |                     } ; def foo[A : Foo](x : List[A]) = implicitly[Foo[A]].apply(x)
defined trait Foo
defined module Foo
foo: [A](x: List[A])(implicit evidence$1: Foo[A])Unit

scala> foo(1)
<console>:8: error: type mismatch;
 found   : Int(1)
 required: List[?]
       foo(1)
           ^
scala> foo(List(1,2,3))
Int
scala> foo(List("a","b","c"))
String
scala> foo(List(1.0))
<console>:8: error: could not find implicit value for evidence parameter of type
 Foo[Double]
       foo(List(1.0))
          ^

Derleyici implicitly[Foo[A]](x) parametreleri ile implicitly dediğimiz anlamına geldiğini düşünüyor beri implicitly[Foo[A]].apply(x) yazmamız gerektiğini unutmayın.

Ayrıca bakınız How to investigate objects/types/etc. from Scala REPL? Where does Scala look for implicits?

CEVAP
4 EKİM 2010, PAZARTESİ


Implicitly Scala 2.8 dairemiz ve Predef olarak tanımlanır:

def implicitly[T](implicit e: T): T = e

Yaygın olarak kullanılırörtülü olmadığını kontrol edindeğertür T mevcut ve bunu geri döndürüreğer öyle bir durum.

retronyms presentation basit örnek)

scala> implicit val a = "test" // define an implicit value of type String
a: java.lang.String = test
scala> val b = implicitly[String] // search for an implicit value of type String and assign it to b
b: String = test
scala> val c = implicitly[Int] // search for an implicit value of type Int and assign it to c
<console>:6: error: could not find implicit value for parameter e: Int
       val c = implicitly[Int]
                         ^

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • dhcrr's channel

    dhcrr's chan

    2 Ocak 2007
  • Manuel Vizcaino

    Manuel Vizca

    27 Mayıs 2008
  • theavettbrothers

    theavettbrot

    9 ŞUBAT 2007