Last active
May 25, 2024 10:19
-
-
Save dacr/b4aab381347ebe59673579cf046dbcc0 to your computer and use it in GitHub Desktop.
Type erasure and solutions to avoid it - work in progress / published by https://github.com/dacr/code-examples-manager #b88b5c9e-7aed-476a-8b44-8ff30015cfd1/9dafe81c9fb8f9ea4416e0b51f080cefc939b444
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// summary : Type erasure and solutions to avoid it - work in progress | |
// keywords : scala, erasure, @testable | |
// publish : gist | |
// authors : David Crosson | |
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2) | |
// id : b88b5c9e-7aed-476a-8b44-8ff30015cfd1 | |
// created-on : 2022-07-04T09:29:07+02:00 | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// run-with : scala-cli $file | |
// --------------------- | |
//> using scala "3.4.2" | |
//> using dep "dev.zio::izumi-reflect:2.1.3" | |
// --------------------- | |
// See - https://medium.com/@sinisalouc/overcoming-type-erasure-in-scala-8f2422070d20 | |
// ----------------------- default - everything is erased type information is lost | |
{ | |
object Extractor { | |
def extract[T](list: List[Any]) = list.flatMap { | |
case element: T => Some(element) | |
case _ => None | |
} | |
} | |
val list = List(1, "string1", List(), "string2") | |
val result = Extractor.extract[String](list) | |
println(result) // List(1, string1, List(), string2) | |
} | |
// ----------------------- ClassTag | |
{ | |
import scala.reflect.ClassTag | |
object Extractor { | |
//def extract[T : ClassTag](list: List[Any]) // Alternative context | |
def extract[T](list: List[Any])(implicit tag: ClassTag[T]) = | |
list.flatMap { | |
case element: T => Some(element) | |
case _ => None | |
} | |
} | |
val list: List[Any] = List(1, "string1", List(), "string2") | |
val result = Extractor.extract[String](list) | |
println(result) // List(string1, string2) | |
} | |
// ----------------------- TypeTag (work in progress required for scala3) | |
{ | |
import izumi.reflect.* | |
object Recognizer { | |
def recognize[T](x: T)(implicit tag: Tag[T]): String = | |
val ref = tag.tag.ref | |
List(ref.repr,ref.longName, ref.shortName, ref.typeArgs).mkString("\n") | |
// match { | |
// case TypeRef(utype, usymbol, args) => | |
// List(utype, usymbol, args).mkString("\n") | |
// } | |
} | |
val list: List[Int] = List(1, 2) | |
val result = Recognizer.recognize(list) | |
println(result) | |
// prints: | |
// scala.type | |
// type List | |
// List(Int) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment