Skip to content

Instantly share code, notes, and snippets.

@tarao
Last active October 7, 2021 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tarao/3948b0d229a350bc554b86edb0aef7e6 to your computer and use it in GitHub Desktop.
Save tarao/3948b0d229a350bc554b86edb0aef7e6 to your computer and use it in GitHub Desktop.
Scala 3.0.2 ClassCastException
object Example {
import scala.collection.IterableOps
import scala.language.implicitConversions
case class Cell[A](value: A)
object Cell {
implicit def toSeq[A, It[X] <: IterableOps[X, It, It[X]]](
cell: Cell[It[A]]
): Seq[A] = cell.value.to(Seq)
}
implicit class Ops[A, It[X] <: IterableOps[X, It, It[X]]](
private val it: It[A]
) extends AnyVal {
def cell(): Cell[It[A]] = Cell(it)
}
}
val l = List(1, 2, 3)
val ll = l.cell().map(i => i * i)
@tarao
Copy link
Author

tarao commented Oct 5, 2021

java.lang.ClassCastException: scala.collection.immutable.$colon$colon cannot be cast to scala.runtime.Nothing$

Workaround:

--- 1.scala     2021-10-05 12:29:58.626057490 +0900
+++ 2.scala     2021-10-05 12:30:12.886196885 +0900
@@ -11,7 +11,7 @@

   implicit class Ops[A, It[X] <: IterableOps[X, It, It[X]]](
     private val it: It[A]
-  ) extends AnyVal {
+  ) {
     def cell(): Cell[It[A]] = Cell(it)
   }
 }

or

--- 1.scala     2021-10-07 19:07:24.129036984 +0900
+++ 3.scala     2021-10-07 19:08:34.149396338 +0900
@@ -10,8 +10,10 @@
   }

   implicit class Ops[A, It[X] <: IterableOps[X, It, It[X]]](
-    private val it: It[A]
+    private val it: A
   ) extends AnyVal {
-    def cell(): Cell[It[A]] = Cell(it)
+    def cell[B, It[X] <: IterableOps[X, It, It[X]]]()(implicit
+      toIt: A <:< It[B]
+    ): Cell[A] = Cell(it)
   }
 }

or

--- 1.scala     2021-10-07 19:07:24.129036984 +0900
+++ 4.scala     2021-10-07 19:09:49.793801654 +0900
@@ -4,8 +4,10 @@

   case class Cell[A](value: A)
   object Cell {
-    implicit def toSeq[A, It[X] <: IterableOps[X, It, It[X]]](
+    implicit def toSeq[A, It[_]](
       cell: Cell[It[A]]
+    )(implicit
+      toIt: It[A] <: IterableOps[A, It, It[A]]
     ): Seq[A] = cell.value.to(Seq)
   }

or replace implicit class with extension

  extension [A, It[X] <: IterableOps[X, It, It[X]]](it: It[A])
    def cell(): Cell[It[A]] = Cell(it)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment