This question already has answers here:
How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?
(11 answers)
Closed 6 years ago.
I'm tying to write a generic function that will convert any type to Option[T]
but somehow it's not working as expected
scala> def toOption[T](obj:Any):Option[T] = obj match {
| case obj:T => Some(obj)
| case _ => None
| }
<console>:11: warning: abstract type pattern T is unchecked since it is eliminated by erasure
case obj:T => Some(obj)
^
toOption: [T](obj: Any)Option[T]
here it's seems ok it return the Option[String]
scala> toOption[String]("abc")
res0: Option[String] = Some(abc)
but here it return Some(def) instead of None
scala> toOption[Int]("def")
res1: Option[Int] = Some(def)
i can't seem to figure the appropriate way to create this generic function ,nor to understand why is that happens, I've already read many posts and questions about type erasure in scala but still can't get it, specific explanation would be a great help!
The type T is not available at runtime because Scala uses type erasure for generics like Java does. So your test case obj:T has not the desired effects and the compiler warned you about that fact.
You may use ClassTags to make the type information available at runtime. ClassTag already implements the conversion to Optional in its unapply method:
scala> import scala.reflect.{classTag,ClassTag};
import scala.reflect.{classTag, ClassTag}
scala> def toOption[T: ClassTag](obj: Any): Option[T] = classTag[T].unapply(obj);
toOption: [T](obj: Any)(implicit evidence$1: scala.reflect.ClassTag[T])Option[T]
scala> toOption[Int](1)
res1: Option[Int] = Some(1)
scala> toOption[String](1)
res2: Option[String] = None
scala> toOption[String]("one")
res3: Option[String] = Some(one)
scala> toOption[Int]("one")
res4: Option[Int] = None
But this doesn't work for generic types as you see here:
scala> toOption[List[Int]](List("one", "two"))
res5: Option[List[Int]] = Some(List(one, two))
scala> res5.get
res6: List[Int] = List(one, two)
scala> res6(0) + res6(1)
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at scala.runtime.BoxesRunTime.unboxToInt(BoxesRunTime.java:101)
... 29 elided
You might want to have two type arguments of the function - the desired type and the actual type:
def toOption[Desired, Actual](obj:Actual):Option[Desired] = ???
And then, I guess, you want to return Some only if the types match:
def toOption[Desired, Actual](obj:Actual)
(implicit ev: Actual =:= Desired = null):Option[Desired] =
if(ev == null)
None
else
Some(ev(obj))
Here you have two type arguments, that might be inconvenient sometimes, when Scala cannot infer both of the arguments. For the same syntax as you used (giving single type argument), you may use the following trick:
class toOptionImpl[Desired] {
def apply[Desired, Actual](obj:Actual)
(implicit ev: Actual =:= Desired = null):Option[Desired] =
if(ev == null)
None
else
Some(ev(obj))
}
def toOption[Desired] = new toOptionImpl[Desired]
It might be used the same way:
toOption[String]("def") == Some("def")
toOption[Int]("def") == None
(You might also look into Miles Sabin's polymorphic functions https://milessabin.com/blog/2012/04/27/shapeless-polymorphic-function-values-1/, https://milessabin.com/blog/2012/05/10/shapeless-polymorphic-function-values-2/)
Related
I am trying to overload a constructor with mutable list of Int and Long , it mentions that the method is already defined.
I need updateList to be either mutable.MutableList[Int] or mutable.MutableList[Long]
object PercentileDistribution {
def apply(updateList: mutable.MutableList[Int], percentileDistribution: PercentileDistribution): PercentileDistribution = {
updateList.foreach { x =>
percentileDistribution.update(x)
}
percentileDistribution
}
def apply(updateList: mutable.MutableList[Long], percentileDistribution: PercentileDistribution): PercentileDistribution = {
updateList.foreach { x =>
percentileDistribution.update(x)
}
percentileDistribution
}
}
Being new to scala I am facing some issues, any help is appreciated.
The error clearly refers to the upcasting that is happening in your code.
An Int can be represented as a Long hence you have essentially written the same method with one methods parameter being the upcasted version of the parameter of the other apply method.
You can simply use the apply method that has the MutableList[Long] type and remove the one with Int.
Follow this documentation from the official scala docs and you will get a good idea as to how types behave in Scala
The error refers to type erasure. The other answer incorrectly states that it is related to casting (although type erasure can lead to casting-related problems).
A quick example done in a Scala REPL session:
scala> class Foo {
| def bar(list: List[Int]) = "ints"
| def bar(list: List[String]) = "strings"
| }
<console>:12: error: double definition:
def bar(list: List[Int]): String at line 11 and
def bar(list: List[String]): String at line 12
have same type after erasure: (list: List)String
def bar(list: List[String]) = "strings"
^
The message here is saying that both bar methods will have a type signature like def bar(list: List): String in the compiled output; type erasure is taking away the [Int] and [String] parameters, making the two methods indistinguishable. It's an annoyance you just have to put up with if you're running code on the JVM.
My recommended workaround is to distinguish the methods by their names, e.g. instead of apply you might call it forInts and forLongs.
Also note that type erasure causes another problem:
scala> List(1,2,3).isInstanceOf[List[String]]
<console>:11: warning: fruitless type test: a value of type List[Int] cannot also be a List[String] (the underlying of List[String]) (but still might match its erasure)
List(1,2,3).isInstanceOf[List[String]]
^
res5: Boolean = true
and
scala> List(1, 2, 3) match {
| case l: List[String] => l // you'd think this shouldn't match, but it does
| }
<console>:12: warning: fruitless type test: a value of type List[Int] cannot also be a List[String] (the underlying of List[String]) (but still might match its erasure)
case l: List[String] => l // you'd think this shouldn't match, but it does
^
res2: List[Int] with List[String] = List(1, 2, 3)
scala> res2.head
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
... 33 elided
Since in the compiled bytecode, List[Int] and List[String] are both only represented as List, the runtime can't actually distinguish between the two, so an isInstanceOf check may provide the wrong answer, possibly leading to ClassCastExceptions as it tries to treat an Int as a String.
In your case you might get away with it, since it is safe to cast an Int to a Long, but it'd be best to avoid unchecked casting altogether.
I'm trying to describe the types which a case class contains.
import shapeless._
import shapeless.ops.hlist.LiftAll
trait Desc[T] {
def description: String
}
case class Foo(f: Int)
object Foo {
implicit val description: Desc[Foo] = new Desc[Foo] { val description = "foo" }
}
case class SomeCaseClass(f: Foo)
val gen = Generic[SomeCaseClass]
val lifted = implicitly[LiftAll[Desc, gen.Repr]].instances.toList
Gives me
could not find implicit value for parameter toTraversableAux: shapeless.ops.hlist.ToTraversable.Aux[shapeless.ops.hlist.LiftAll[Playground.this.Desc,Playground.this.gen.Repr]#Out,List,Lub]
not enough arguments for method toList: (implicit toTraversableAux: shapeless.ops.hlist.ToTraversable.Aux[shapeless.ops.hlist.LiftAll[Playground.this.Desc,Playground.this.gen.Repr]#Out,List,Lub])toTraversableAux.Out.
Unspecified value parameter toTraversableAux.
Scastie here: https://scastie.scala-lang.org/bXu71pMQQzCqrrsahVBkWA
When you summon an implicit instance with implicitly[LiftAll[Desc, gen.Repr]] then the dependent type Out of LiftAll is lost, so the compiler doesn't know which type exactly instances will return.
To work around this problem most typeclasses in Shapeless define an apply method in their companion object which does retain all dependent type information. It's the reason that you can use gen.Repr in a meaningful way after calling val gen = Generic[SomeCaseClass]. For some reason however LiftAll.apply was not implemented in this way. So that leaves you the option of implementing your own implicitly, or since you're using Shapeless anyway, use its the which is supposed to be a better implicitly.
scala> def impl[T <: AnyRef](implicit ev: T): ev.type = ev
impl: [T <: AnyRef](implicit ev: T)ev.type
scala> impl[LiftAll[Desc, gen.Repr]].instances.toList
res1: List[Desc[Foo]] = List(Foo$$anon$1#40b3708a)
scala> the[LiftAll[Desc, gen.Repr]].instances.toList
res2: List[Desc[Foo]] = List(Foo$$anon$1#40b3708a)
You can see the difference here in the inferred types that the REPL displays:
scala> impl[LiftAll[Desc, gen.Repr]]
res3: LiftAll.Aux[Desc,Foo :: HNil,Desc[Foo] :: HNil] = shapeless.ops.hlist$LiftAll$$anon$206#384d060c
scala> implicitly[LiftAll[Desc, gen.Repr]]
res4: LiftAll[Desc,gen.Repr] = shapeless.ops.hlist$LiftAll$$anon$206#30787774
This seems like a simple question that I was sure have been asked before, but couldn't find what I was looking for.
How can one write a function that takes a collection as an argument (or anything that can be treated as a collection), perform some operations on it, and return a collection of the same type?
e.g:
scala> def foo[Repr <% Traversable[String]](repr: Repr) = repr.map(_.size)
foo: [Repr](repr: Repr)(implicit evidence$1: Repr => Traversable[String])Traversable[Int]
this works ok on some collections:
scala> foo(Vector("Hello","World"))
res0: Traversable[Int] = Vector(5, 5)
but surprising when I tried on other collections (e.g. Option):
scala> foo(Some("HelloWorld"))
res1: Traversable[Int] = List(10)
a small problem is the return type Traversable, which ideally would be the type of whatever was given to the method. the bigger problem is the actual implementation type: an Option became a List.
it gets even worse, when tried on classes (that behaves like collections) but have no implicit in scope for them. e.g: Try:
scala> import scala.util._
import scala.util._
scala> foo(Success("HelloWorld"))
<console>:12: error: No implicit view available from scala.util.Success[String] => Traversable[String].
foo(Success("HelloWorld"))
^
So, is there a way, to write a generic function, that when given a "collection like" argument, can operate on it's elements and return the correct type?
ideally, I would like to use it on anything (even Future, and Try) , but for my specific usage, I can do with just real collections & Option.
EDIT:
to illustrate a possible solution, (which forces me to copy&paste code, and so, is not what i'm looking for) is to simply write both functions without view bounds:
scala> :paste
// Entering paste mode (ctrl-D to finish)
def foo[Repr <: Traversable[String]](repr: Repr) = repr.map(_.size)
def foo(repr: Option[String]) = repr.map(_.size)
// Exiting paste mode, now interpreting.
foo: [Repr <: Traversable[String]](repr: Repr)Traversable[Int] <and> (repr: Option[String])Option[Int]
foo: [Repr <: Traversable[String]](repr: Repr)Traversable[Int] <and> (repr: Option[String])Option[Int]
scala> foo(Vector("bar"))
res2: Traversable[Int] = Vector(3)
scala> foo(Some("bar"))
res3: Option[Int] = Some(3)
The concept of mapping is represented by functors. One way to easily provide functor implementations for common classes is to use the scalaz library:
import scala.language.higherKinds
import scalaz.Functor
import scalaz.Scalaz._
def foo[El <: String, Coll[_]](repr: Coll[El])(implicit ev: Functor[Coll]) =
repr.map(_.size)
Now, this just works for List, Vector and Future:
scala> foo(Vector("Hello","World"))
res1: scala.collection.immutable.Vector[Int] = Vector(5, 5)
scala> foo(List("Hello","World"))
res2: List[Int] = List(5, 5)
scala> import scala.concurrent.Future
scala> import scala.concurrent.ExecutionContext.Implicits.global
scala> foo(Future("HelloWorld")) andThen PartialFunction(println(_))
Success(10)
Using it with Some is a bit of a problem, because only Option has a Functor implementation, not Some:
scala> foo(Some("HelloWorld"))
<console>:12: error: could not find implicit value for parameter ev: scalaz.Functor[Some]
foo(Some("HelloWorld"))
^
So you have to provide Option instead of Some to foo:
scala> foo(Some("HelloWorld"): Option[String])
res3: Option[Int] = Some(10)
scala> foo(Option("HelloWorld"))
res4: Option[Int] = Some(10)
scala> foo("HelloWorld".some) // This is from scalaz
res5: Option[Int] = Some(10)
And scalaz doesn't have any typeclass implementations for Try, so if you want to use Functor with Try, you'll have to provide the implementation yourself:
import scala.util.Try
import scalaz.Functor
implicit object TryIsFunctor extends Functor[Try] {
def map[A, B](fa: Try[A])(f: A => B): Try[B] = fa map f
}
Then foo will work with Try, but similar to Option, the argument should have the type Try, instead of Success or Failure:
scala> foo(Try("HelloWorld"))
res9: scala.util.Try[Int] = Success(10)
Also, I believe, there are no Functor implementations in scalaz for more general collection types, like Iterable or Seq.
Out of the common higher-order functions Functor only supports map. So to use flatMap and filter you have to provide different typeclasses instead of Functor. For example, scalaz.Monad supports map and flatMap, and scalaz.MonadPlus supports map, flatMap and filter.
And if you don't want to use scalaz, you'd probably have to make something very similar yourself with typeclasses, to get a good result type instead of Traversable. For example, using CanBuildFrom from the standard library.
I do think Kolmar is right about the general problem, but Scala does support duck-typing, so you can do this:
def foo[T[V]](duck: {def map[U](value: String=>U): T[_]}) ={
duck.map(_.size)
}
foo(Vector("bar")).toVector //> res0: Vector[_$2] = List(3)
foo(Some("bar")) //> res1: Option[_$2] = Some(3)
(toVector just to force the eval of the iterator that otherwise results)
I'm confused as how isInstanceOf works in Scala. If I do something like this:
val x: Int = 5
x.isInstanceOf[Int]
Given that Scala does type erasure, shouldn't the JVM remove all type information during runtime?
It's not all type information, just information about generic types. Consider this:
scala> val l = List("foo")
l: List[String] = List(foo)
scala> l.isInstanceOf[List[String]]
res0: Boolean = true
scala> l.isInstanceOf[List[Int]]
<console>:9: warning: fruitless type test: a value of type List[String] cannot also be a List[Int] (the underlying of List[Int]) (but still might match its erasure)
l.isInstanceOf[List[Int]]
^
res1: Boolean = true
They both return true, because the erased type is List.
Given:
case class Person(name: String)
and trying to do:
scala> List(Person("Tom"), Person("Bob")).sorted
results in a complaint about missing Ordering.
<console>:8: error: could not find implicit value for parameter ord: Ordering[Person]
List(Person("Tom"), Person("Bob")).sorted
However this:
case class Person(name: String) extends Ordered[Person] {
def compare(that: Person) = this.name compare that.name }
works fine as expected:
scala> List(Person("Tom"), Person("Bob")).sorted
res12: List[Person] = List(Person(Bob), Person(Tom))
although there's no Ordering or implicits involved.
Question #1: what's going on here? (My money is on something implicit...)
However, given the above and the fact that this:
scala> Person("Tom") > Person("Bob")
res15: Boolean = true
works, and that also this:
scala> List(Some(2), None, Some(1)).sorted
works out of the box:
res13: List[Option[Int]] = List(None, Some(1), Some(2))
I would expect that this:
scala> Some(2) > Some(1)
would also work, however it does not:
<console>:6: error: value > is not a member of Some[Int]
Some(2) > Some(1)
Question #2: why not, and how can I get it to work?
If you install the slightly-too-magical-for-default-scope bonus implicits, you can compare options like so:
scala> import scala.math.Ordering.Implicits._
import scala.math.Ordering.Implicits._
scala> def cmpSome[T: Ordering](x: Option[T], y: Option[T]) = x < y
cmpSome: [T](x: Option[T], y: Option[T])(implicit evidence$1: Ordering[T])Boolean
The import gives you an implicit from an Ordering to the class with the infix operations, so that it's enough to have the Ordering without another import.
Concerning your first question: Ordered[T] extends Comparable[T]. The Ordering companion object provides an implicit Ordering[T] for any value that can be converted into a Comparable[T]:
implicit def ordered[A <% Comparable[A]]: Ordering[A]
There is no implicit conversion A : Ordering => Ordered[A] - that's why Some(1) > Some(2) will not work.
It is questionable if it is a good idea to define such a conversion as you may end up wrapping your objects into Ordered instances and then create an Ordering of that again (and so on...). Even worse: you could create two Ordered instances with different Ordering instances in scope which is of course not what you want.
The definition of List's sorted method is:
def sorted [B >: A] (implicit ord: Ordering[B]): List[A]
So yes, implicit things are happening, but many classes in the standard library have implicit objects associated with them without you having to import them first.
The Ordering companion object defines a bunch of implicit orderings. Among these is an OptionOrdering and IntOrdering, which helps explain the ability of a list to call sorted.
To gain the ability to use operators when there is an implicit conversion available, you need to import that object, for example:
def cmpSome(l:Option[Int], r:Option[Int])(implicit ord:Ordering[Option[Int]]) = {
import ord._
l < r
}
scala> cmpSome(Some(0), Some(1))
res2: Boolean = true
To answer your second question, why can't you do this: Some(2) > Some(1)
You can, with an import and working with Option[Int] rather than Some[Int].
# import scala.math.Ordering.Implicits._
import scala.math.Ordering.Implicits._
# Some(2) > Some(1) // doesn't work
cmd11.sc:1: value > is not a member of Some[Int]
val res11 = Some(2) > Some(1)
^
Compilation Failed
# (Some(2): Option[Int]) > (Some(1): Option[Int]) // Option[Int] works fine
res11: Boolean = true
# Option(2) > Option(1)
res12: Boolean = true
# (None: Option[Int]) > (Some(1): Option[Int])
res13: Boolean = false
In practise your types will probably be of Option[Int] rather than Some[Int] so it won't be so ugly and you won't need the explicit upcasting.
I assume you understand why sorted does not work when you do not pass in an Ordering and none is available in scope.
As to why the sorted function works when you extend your class from Ordered trait. The answer is that when you extend from Ordered trait, the code type checks as the trait contains function like <,> etc. So there is no need to do implicit conversion and hence no complains about the missing implicit Ordering.
As for your second question, Some(2) > Some(1) will not work because Some does not extend the trait Ordered, neither does there seem to be any implicit function in scope that implicitly converts a Some to something that has the function >
Thanks for a detailed question with examples.
My answer is based what I learnt from a great article here: http://like-a-boss.net/2012/07/30/ordering-and-ordered-in-scala.html
All credit to the author here.
Quoting the article:
Coming back to our Box example - the scala library defines an implicit conversion between Ordered[T] and Ordering[T] and vice-versa.
The companion object of Ordered in https://github.com/scala/scala/blob/2.12.x/src/library/scala/math/Ordered.scala provides the required conversion here:
/** Lens from `Ordering[T]` to `Ordered[T]` */
implicit def orderingToOrdered[T](x: T)(implicit ord: Ordering[T]): Ordered[T] =
new Ordered[T] { def compare(that: T): Int = ord.compare(x, that) }
However the reverse conversion isn't defined and I am not sure why?