Last active
April 2, 2023 10:14
-
-
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/630224776ca57356d8b878c030bb35685076918f
This file contains 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.2.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