Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract types puzzler

Given class A is:

class A {
  type R
}

Why does the following code compile (and run too)?

val a = new A
println(a)

Isn't A supposed to be abstract?

like image 930
user976845 Avatar asked Jul 14 '26 19:07

user976845


2 Answers

A isn't abstract. If it were abstract then it would look like:

abstract class A {
  type R
}

or

trait A {
  type R
}

Now, I can't find it in the spec (haven't had much luck with finding stuff in there lately) but I've seen this before. If the type isn't used, then it appears as though it's not evaluated, which means the lack of its completeness is not an issue.

If you really want A to be abstract, make it so using one of the above definitions instead.

like image 69
Derek Wyatt Avatar answered Jul 17 '26 17:07

Derek Wyatt


Just to elaborate on @alex22's comment:

scala> trait T { type R; def foo(r: R) = r }
defined trait T

scala> new T{}.foo("")
<console>:12: error: type mismatch;
 found   : java.lang.String("")
 required: _6.R where val _6: java.lang.Object with T
              new T{}.foo("")
                          ^

scala> new T{ type R = String }.foo("")
res37: java.lang.String = ""
like image 42
retronym Avatar answered Jul 17 '26 17:07

retronym



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!