Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Idiomatic Scala doesn't care at all about erased generics. With implicits and macros and libraries built upon them like shapeless, you can do everything you'd want to do with reified generics and more and it'll be done and statically checked at compile time instead of dynamically at run time.


I know there are ways like typetags to work around it, but on the JVM this is never going to run without extra work:

    def erased[T](xs: List[T]) : String = {
      xs match {
        case ns : List[Int] =>"Natural numbers"
        case fs : List[Double] => "Floating point numbers"
        case _ : List[T] => "Something else"
      }
    }
    System.out.println(erased(List(1,2,3)))
    System.out.println(erased(List(1.0,2.0,3.0)))
Which is purely because of a JVM runtime limitation. Will native scala behave identically to JVM scala in this case or will you be able to improve?


The part that you're missing is that code like this in Scala is totally unnecessary and it never happens:

    case ns : List[Int] =>
Worst case scenario, you can always do the following and it would be more idiomatic, no type erasure standing in the way:

    val listInt = listAny.collect { case x:Int => x }
    val listDouble = listAny.collect { case x:Double => x }
But even that is totally unnecessary. You know why? Because your function does not make sense. What could you possibly do with a function that takes a List[T] and returns a String?

The only way this would make sense would be if you are talking about a List[Any] deserialized from somewhere (like some shitty JSON library). But then in Scala we don't really work with Any, that should never happen and if you see libraries that use Any in their API, drop them like they are hot ;-)

> Which is purely because of a JVM runtime limitation

No it's not. Talk to compiler authors. This is actually a freedom, because by introducing reified generics in the runtime, then language designers either have to deal with inefficiencies due to boxing because of extra conversions, or to limit their type system, so for example you can say goodbye to higher-kinded types. A runtime that has reified generics is not a multi-language runtime. In fact many languages are doing type erasure. Haskell is doing type erasure. And why shouldn't it, I mean, type casting and isInstanceOf checks make no sense in Haskell.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: