estatico / scala-newtype

NewTypes for Scala with no runtime overhead
Apache License 2.0
540 stars 31 forks source link

Feature Request: match case and isInstanceOf #3

Closed schlichtanders closed 6 years ago

schlichtanders commented 6 years ago

it would be awesom if the NewType and NewSubType would also behave respectively when applied to isInstanceOf[_] and case _:Type =>

while a NewType is indeed not recognized for function arguments

import io.estatico.newtype.NewType

object Point extends NewType.Default[(Int, Int)]
val p = Point((1,2))

def add(t:(Int, Int)): Int = t._1 + t._2
add(p)  // will raise an error

The following does not work as hoped for

p.isInstanceOf[(_, _)]  // returns <true>, however we would like to have <false>
p match {
  case p: (_, _) => "bad"
  case _ => "good"
}  // returns "bad"

Is this an underlying systematic issue or can this be adapted to fit the NewType / NewSubType distinction?

carymrobbins commented 6 years ago

This has to do with the fact that isInstanceOf and case p: (_, _) are performing runtime type checking. This would technically be a "feature" not a "bug" in the sense that it is the premise for why we use NewType in the first place.

NewType creates a new type only at compile time. At runtime it will always be the underlying Repr type. This is good so we don't incur unnecessary allocations when all we want is to have a distinct type to enforce correctness at compile time but don't want to pay for it at runtime.

Hope this makes sense and sorry for the delay in response!

schlichtanders commented 6 years ago

thanks a lot for the explanation! having case matching being a runtime thing, newtypes in scala are quite less powerful then in haskell where case matching is a compile thing

Still nice to have and thanks a lot for supporting it!

carymrobbins commented 6 years ago

You're welcome!

Regarding Haskell, note that you couldn't really do runtime type pattern matching anyway. Pattern matching is always used for constructor matching and/or destructuring. Of course, there are dirty hacks you could do to simulate it, but it's really not the same as in Scala where pattern matching also translates to isInstanceOf checks.