Is Scala strongly typed ? Do you have example how is it being reflected in the language type system? Does Scala allow type punning? Does it allow coercion?
Does Scala have polytypes like ML?
Thank you!
Is Scala strongly typed ? Do you have example how is it being reflected in the language type system? Does Scala allow type punning? Does it allow coercion?
Does Scala have polytypes like ML?
Thank you!
Because of strong typing, it does not allow "type punning" as I understand it is used in the C language. However, you have sub-typing, therefore you can safely use a value of type A
where a value of type B
is requested, if A <: B
(A
is a sub-type of or more specific than B
).
You can coerce a type using a.asInstanceOf[B]
, however this will be type-checked at runtime and causes an exception to be thrown if a
is not a sub-type of B
, with the exception of higher-kinded types which are erased on the JVM, meaning that such an exception may be thrown only later when actual values of the type parameters are referenced.
Another exception is structural typing which could be thought of as a "punning", although type-safe:
// ordinary type
trait Foo {
def bar: Int
}
// structural type
type Bar = Any {
def bar: Int
}
def test(b: Bar) = b.bar
test(new Foo { val bar = 1234 }) // allowed
This is considered an advanced feature that is rarely used and may even be deprecated in future Scala versions. It requires runtime reflection and thus comes with a performance penalty.
You may also abandon the static type system using the special Dynamic
trait. Or you may do crazy stuff using macros to implement your own sort of punning.
No idea, not an ML expert. But if polytype just means this, then this looks like ordinary higher-kinded (parametrised) types or "generics", and the answer would be Yes.
def identity[A](x: A): A = x
trait Option[+A] { def get: A }
"1.0" + 5
, scala
converts 5
to string and result is "1.05"
. Scala behaves like a weakly typed language here. –
Hairpiece 1 == "1"
which will return false
for strongly typed languages, which don't do coercion –
Balcke © 2022 - 2024 — McMap. All rights reserved.