What I want to do is returning generics type in Scala function by using TypeTag. Here is the example code.
trait Parent[T]
object IntChild extends Parent[Int]
object StringChild extends Parent[String]
object SomeClass {
def of[A: TypeTag]: Parent[T] = {
getElementType[A] match {
case Int => IntChild
case String => StringChild
}
}
}
SomeClass.of[Array[Int]]
But it throws a compile error. Because the returned type of of method is not fixed in the compile type. Is there any way to get the type information from TypeTag and embed the type in the returned type?
What I am expecting is like
// T is inferred from TypeTag A.
def of[A: TypeTag, T]: Parent[T] = {
//...
}
I found this code also has not passed compile. So we need to fix the type information inferred from A's TypeTag.
def of[A: TypeTag]: Parent[_] = {
//...
}
This is the error.
type mismatch;
[error] found : Array[Int]
[error] required: Array[_$1]
How can I get the element type in advance?
I'm not sure it's possible with those definitions. How about changing the definitions a little?
trait Parent[T]
implicit object IntChild extends Parent[Int]
implicit object StringChild extends Parent[String]
object SomeClass {
def of[A: Parent]: Parent[A] = implicitly
}
This makes sure everything is done at the type level so that you get the return type you want. It requires the implicit modifier on IntChild and StringChild. There's no need to have another type parameter named T, as it would always be the same as A in your example.
Why Scala compiler cannot compile next code :
trait Profile {}
class SomeProfile extends Profile
trait Foo {
def get[T <: Profile]: Option[T]
}
object Example {
val foo: Foo = new Foo {
// This works (but might give runtime exception), but it is not ugly? :)
def get[T <: Profile]: Option[T] = Some((new SomeProfile).asInstanceOf[T])
}
val foo2: Foo = new Foo {
// This does not compile with type mismatch :(
def get[T <: Profile]: Option[T] = Some(new SomeProfile)
}
}
Compiler says:
type mismatch;
found : Playground.this.SomeProfile
required: T
But SomeProfile is T, no?
Update:
I want to implement this trait DatabaseConfigProvider with exact type and do it in this way:
val dc: DatabaseConfig[JdbcProfile] = ???
val prov = new DatabaseConfigProvider {
def get[P <: BasicProfile] = dc.asInstanceOf[DatabaseConfig[P]]
}
which looks ugly because of asInstanceOf.
You wrongly declared input argument. Try below:
trait Profile {}
class SomeProfile() extends Profile
trait Foo {
def get[T >: Profile]: Option[T]
}
object Example {
val foo2: Foo = new Foo {
override def get[T >: Profile]: Option[T] = Some(new SomeProfile())
}
}
Explanation for what :> does, you could find easily in Stackoverflow (e.g.: What does [B >: A] do in Scala?)
Output type of your method get is defined by caller. You added type bounds (as T <: Profile) but this does only mean limitations for caller. Any casts (as you did) will fail at runtime if caller ask for another subtype of Profile than one you casted.
If you provide more details on what you expect to get as result, I can extend answer with specific advise how to get it.
I´m trying to create an implicit class using generic, here the class
object Utils {
implicit class optionUtils(option: Option[Any]) {
def sortedList[T]:List[T] = {
val list:List[T] = option.get.asInstanceOf[List[T]]
list.sorted[T]
}
}
}
And here the invocation
jsonResponse.get("products").sortedList[String]
But seems like sorted is not compiling, and the compiler says.
Error:(8, 18) not enough arguments for method sorted: (implicit ord: scala.math.Ordering[T])List[T].
Unspecified value parameter ord.
list.sorted[T]
^
Any idea how to make it works?.
Regards.
You have to tell the compiler that T is restricted to an order-able type.
def sortedList[T: Ordering]:List[T] = { ...
There's a situation where I get a compiler error for an implicit conversion if I do not include a Manifest:
import scala.language.implicitConversions
abstract class Thing[+A] {
def get:A
}
case class SubThing[+A](a:A) extends Thing[A] {
def get = a
}
object Thing {
implicit def anyToThing[A](a:A):Thing[A] = SubThing(a)
}
object Funcs {
def f(x:Thing[Int]) = x.get + 1
def f(x:Thing[Double]) = x.get + 1.0
}
object Main {
def main(args:Array[String]) = {
println(Funcs.f(1))
}
}
will give
error: ambiguous reference to overloaded definition,
both method f in object Funcs of type (x: Thing[Double])Double
and method f in object Funcs of type (x: Thing[Int])Int
match argument types (Int) and expected result type Any
println(Funcs.f(1))
^
However, if I pass in an implicit Manifest for A in the implicit conversion:
import scala.language.implicitConversions
abstract class Thing[+A] {
def get:A
}
case class SubThing[+A](a:A) extends Thing[A] {
def get = a
}
object Thing {
implicit def anyToThing[A:Manifest](a:A):Thing[A] = SubThing(a)
}
object Funcs {
def f(x:Thing[Int]) = x.get + 1
def f(x:Thing[Double]) = x.get + 1.0
}
object Main {
def main(args:Array[String]) = {
println(Funcs.f(1))
}
}
Causes the code to compile fine. Why is this the case? There's a real example of this in our codebase, which gives a lot of 'no Manifest for T' errors if you're relying on the implicit conversion in generic situations, which are eliminated by creating the wrapper class explicitly; however if we could just get the Manifest out of that implicit conversion that would be ideal. Why is it required, or is there another way to accomplish the same thing while avoiding Manifests?
This was caused by scala's automatic promotion of Ints to Double, which made the implicit conversion ambiguous. When the manifest is included, it creates an implicit parameter that causes the function resolution to become unambiguous, just as DummyImplicit implicit parameters are used to combat overloaded-function ambiguity that's due to the type erasure as Ivan mentioned.
I believe this happens because once converted to Thing, type erasure kicks in and its no longer a Thing[Int] or Thing[Double] but a Thing[_] and hence the following method overloading does not work.
object Funcs {
def f(x:Thing[Int]) = x.get + 1
def f(x:Thing[Double]) = x.get + 1.0
}
The manifest is where my understanding breaks down a little because I have never dealt with it much, but I guess it presevies the type so that the method overloading works.
You could work around this with macros I believe, although that would preclude calling Funcs.f() on anything the compiler didnt know for sure was an Int or Double.
I wrote this in scala and it won't compile:
class TestDoubleDef{
def foo(p:List[String]) = {}
def foo(p:List[Int]) = {}
}
the compiler notify:
[error] double definition:
[error] method foo:(List[String])Unit and
[error] method foo:(List[Int])Unit at line 120
[error] have same type after erasure: (List)Unit
I know JVM has no native support for generics so I understand this error.
I could write wrappers for List[String] and List[Int] but I'm lazy :)
I'm doubtful but, is there another way expressing List[String] is not the same type than List[Int]?
Thanks.
I like Michael Krämer's idea to use implicits, but I think it can be applied more directly:
case class IntList(list: List[Int])
case class StringList(list: List[String])
implicit def il(list: List[Int]) = IntList(list)
implicit def sl(list: List[String]) = StringList(list)
def foo(i: IntList) { println("Int: " + i.list)}
def foo(s: StringList) { println("String: " + s.list)}
I think this is quite readable and straightforward.
[Update]
There is another easy way which seems to work:
def foo(p: List[String]) { println("Strings") }
def foo[X: ClassTag](p: List[Int]) { println("Ints") }
def foo[X: ClassTag, Y: ClassTag](p: List[Double]) { println("Doubles") }
For every version you need an additional type parameter, so this doesn't scale, but I think for three or four versions it's fine.
[Update 2]
For exactly two methods I found another nice trick:
def foo(list: => List[Int]) = { println("Int-List " + list)}
def foo(list: List[String]) = { println("String-List " + list)}
Instead of inventing dummy implicit values, you can use the DummyImplicit defined in Predef which seems to be made exactly for that:
class TestMultipleDef {
def foo(p:List[String]) = ()
def foo(p:List[Int])(implicit d: DummyImplicit) = ()
def foo(p:List[java.util.Date])(implicit d1: DummyImplicit, d2: DummyImplicit) = ()
}
To understand Michael Krämer's solution, it's necessary to recognize that the types of the implicit parameters are unimportant. What is important is that their types are distinct.
The following code works in the same way:
class TestDoubleDef {
object dummy1 { implicit val dummy: dummy1.type = this }
object dummy2 { implicit val dummy: dummy2.type = this }
def foo(p:List[String])(implicit d: dummy1.type) = {}
def foo(p:List[Int])(implicit d: dummy2.type) = {}
}
object App extends Application {
val a = new TestDoubleDef()
a.foo(1::2::Nil)
a.foo("a"::"b"::Nil)
}
At the bytecode level, both foo methods become two-argument methods since JVM bytecode knows nothing of implicit parameters or multiple parameter lists. At the callsite, the Scala compiler selects the appropriate foo method to call (and therefore the appropriate dummy object to pass in) by looking at the type of the list being passed in (which isn't erased until later).
While it's more verbose, this approach relieves the caller of the burden of supplying the implicit arguments. In fact, it even works if the dummyN objects are private to the TestDoubleDef class.
Due to the wonders of type erasure, the type parameters of your methods' List get erased during compilation, thus reducing both methods to the same signature, which is a compiler error.
As Viktor Klang already says, the generic type will be erased by the compiler. Fortunately, there's a workaround:
class TestDoubleDef{
def foo(p:List[String])(implicit ignore: String) = {}
def foo(p:List[Int])(implicit ignore: Int) = {}
}
object App extends Application {
implicit val x = 0
implicit val y = ""
val a = new A()
a.foo(1::2::Nil)
a.foo("a"::"b"::Nil)
}
Thanks for Michid for the tip!
If I combine Daniels response and Sandor Murakozis response here I get:
#annotation.implicitNotFound(msg = "Type ${T} not supported only Int and String accepted")
sealed abstract class Acceptable[T]; object Acceptable {
implicit object IntOk extends Acceptable[Int]
implicit object StringOk extends Acceptable[String]
}
class TestDoubleDef {
def foo[A : Acceptable : Manifest](p:List[A]) = {
val m = manifest[A]
if (m equals manifest[String]) {
println("String")
} else if (m equals manifest[Int]) {
println("Int")
}
}
}
I get a typesafe(ish) variant
scala> val a = new TestDoubleDef
a: TestDoubleDef = TestDoubleDef#f3cc05f
scala> a.foo(List(1,2,3))
Int
scala> a.foo(List("test","testa"))
String
scala> a.foo(List(1L,2L,3L))
<console>:21: error: Type Long not supported only Int and String accepted
a.foo(List(1L,2L,3L))
^
scala> a.foo("test")
<console>:9: error: type mismatch;
found : java.lang.String("test")
required: List[?]
a.foo("test")
^
The logic may also be included in the type class as such (thanks to jsuereth):
#annotation.implicitNotFound(msg = "Foo does not support ${T} only Int and String accepted")
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)
Which gives:
scala> #annotation.implicitNotFound(msg = "Foo does not support ${T} only Int and String accepted")
| 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>:32: error: Foo does not support Double only Int and String accepted
foo(List(1.0))
^
Note that we have to write implicitly[Foo[A]].apply(x) since the compiler thinks that implicitly[Foo[A]](x) means that we call implicitly with parameters.
There is (at least one) another way, even if it is not too nice and not really type safe:
import scala.reflect.Manifest
object Reified {
def foo[T](p:List[T])(implicit m: Manifest[T]) = {
def stringList(l: List[String]) {
println("Strings")
}
def intList(l: List[Int]) {
println("Ints")
}
val StringClass = classOf[String]
val IntClass = classOf[Int]
m.erasure match {
case StringClass => stringList(p.asInstanceOf[List[String]])
case IntClass => intList(p.asInstanceOf[List[Int]])
case _ => error("???")
}
}
def main(args: Array[String]) {
foo(List("String"))
foo(List(1, 2, 3))
}
}
The implicit manifest paramenter can be used to "reify" the erased type and thus hack around erasure. You can learn a bit more about it in many blog posts,e.g. this one.
What happens is that the manifest param can give you back what T was before erasure. Then a simple dispatch based on T to the various real implementation does the rest.
Probably there is a nicer way to do the pattern matching, but I haven't seen it yet. What people usually do is matching on m.toString, but I think keeping classes is a bit cleaner (even if it's a bit more verbose). Unfortunately the documentation of Manifest is not too detailed, maybe it also has something that could simplify it.
A big disadvantage of it is that it's not really type safe: foo will be happy with any T, if you can't handle it you will have a problem. I guess it could be worked around with some constraints on T, but it would further complicate it.
And of course this whole stuff is also not too nice, I'm not sure if it worth doing it, especially if you are lazy ;-)
Instead of using manifests you could also use dispatchers objects implicitly imported in a similar manner. I blogged about this before manifests came up: http://michid.wordpress.com/code/implicit-double-dispatch-revisited/
This has the advantage of type safety: the overloaded method will only be callable for types which have dispatchers imported into the current scope.
Nice trick I've found from http://scala-programming-language.1934581.n4.nabble.com/disambiguation-of-double-definition-resulting-from-generic-type-erasure-td2327664.html
by Aaron Novstrup
Beating this dead horse some more...
It occurred to me that a cleaner hack is to use a unique dummy type
for each method with erased types in its signature:
object Baz {
private object dummy1 { implicit val dummy: dummy1.type = this }
private object dummy2 { implicit val dummy: dummy2.type = this }
def foo(xs: String*)(implicit e: dummy1.type) = 1
def foo(xs: Int*)(implicit e: dummy2.type) = 2
}
[...]
I tried improving on Aaron Novstrup’s and Leo’s answers to make one set of standard evidence objects importable and more terse.
final object ErasureEvidence {
class E1 private[ErasureEvidence]()
class E2 private[ErasureEvidence]()
implicit final val e1 = new E1
implicit final val e2 = new E2
}
import ErasureEvidence._
class Baz {
def foo(xs: String*)(implicit e:E1) = 1
def foo(xs: Int*)(implicit e:E2) = 2
}
But that will cause the compiler to complain that there are ambiguous choices for the implicit value when foo calls another method which requires an implicit parameter of the same type.
Thus I offer only the following which is more terse in some cases. And this improvement works with value classes (those that extend AnyVal).
final object ErasureEvidence {
class E1[T] private[ErasureEvidence]()
class E2[T] private[ErasureEvidence]()
implicit def e1[T] = new E1[T]
implicit def e2[T] = new E2[T]
}
import ErasureEvidence._
class Baz {
def foo(xs: String*)(implicit e:E1[Baz]) = 1
def foo(xs: Int*)(implicit e:E2[Baz]) = 2
}
If the containing type name is rather long, declare an inner trait to make it more terse.
class Supercalifragilisticexpialidocious[A,B,C,D,E,F,G,H,I,J,K,L,M] {
private trait E
def foo(xs: String*)(implicit e:E1[E]) = 1
def foo(xs: Int*)(implicit e:E2[E]) = 2
}
However, value classes do not allow inner traits, classes, nor objects. Thus also note Aaron Novstrup’s and Leo’s answers do not work with a value classes.
I didn't test this, but why wouldn't an upper bound work?
def foo[T <: String](s: List[T]) { println("Strings: " + s) }
def foo[T <: Int](i: List[T]) { println("Ints: " + i) }
Does the erasure translation to change from foo( List[Any] s ) twice, to foo( List[String] s ) and foo( List[Int] i ):
http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#FAQ108
I think I read that in version 2.8, the upper bounds are now encoded that way, instead of always an Any.
To overload on covariant types, use an invariant bound (is there such a syntax in Scala?...ah I think there isn't, but take the following as conceptual addendum to the main solution above):
def foo[T : String](s: List[T]) { println("Strings: " + s) }
def foo[T : String2](s: List[T]) { println("String2s: " + s) }
then I presume the implicit casting is eliminated in the erased version of the code.
UPDATE: The problem is that JVM erases more type information on method signatures than is "necessary". I provided a link. It erases type variables from type constructors, even the concrete bound of those type variables. There is a conceptual distinction, because there is no conceptual non-reified advantage to erasing the function's type bound, as it is known at compile-time and does not vary with any instance of the generic, and it is necessary for callers to not call the function with types that do not conform to the type bound, so how can the JVM enforce the type bound if it is erased? Well one link says the type bound is retained in metadata which compilers are supposed to access. And this explains why using type bounds doesn't enable overloading. It also means that JVM is a wide open security hole since type bounded methods can be called without type bounds (yikes!), so excuse me for assuming the JVM designers wouldn't do such an insecure thing.
At the time I wrote this, I didn't understand that stackoverflow was a system of rating people by quality of answers like some competition over reputation. I thought it was a place to share information. At the time I wrote this, I was comparing reified and non-reified from a conceptual level (comparing many different languages), and so in my mind it didn't make any sense to erase the type bound.