Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit Conversion from Any to Dynamic

Why isn't the following working? (Yes, I am working with 2.9.0final and turned the "-Xexperimental" option on.)

implicit def any2Dynamic(a: Any) = new Dynamic {
  def applyDynamic(name: String)(args: Any*) = {
    println(a + name)
  }
}

"Say".hello // value hello is not a member of java.lang.String

One can argue about how meaningful this is... If this would work as expected what precedence will take place at "Say".toInt: StringLike.toInt or (new Dynamic {...}).applyDynamic("toInt")?

like image 625
Peter Schmitz Avatar asked May 15 '11 12:05

Peter Schmitz


People also ask

Is there an implicit conversion from dynamic to any type?

10.2.An implicit dynamic conversion exists from an expression of type dynamic to any type T .

What is an implicit conversion?

An implicit conversion sequence is the sequence of conversions required to convert an argument in a function call to the type of the corresponding parameter in a function declaration. The compiler tries to determine an implicit conversion sequence for each argument.

What is implicit type casting?

An implicit cast is a cast that the database server can invoke automatically when it encounters data types that cannot be compared with built-in casts. This type of cast enables the database server to automatically handle conversions between other data types.

What is dynamic return type in C#?

In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.


1 Answers

The compiler first looks for an implicit view from String => { def hello: ? }. That fails, so it then checks if String <: Dynamic. These are not combined.

This dynamic apply feature has not been finalized -- in Scala 2.9.0 it is experimental, and subject to change. But I doubt this would be included, as with such an implicit, you throw all type safety out the window. You would never get a compile error for misspelled method names or incorrect argument types. What is your use case?

like image 183
retronym Avatar answered Oct 20 '22 15:10

retronym