Hard mismatches in single point types

I have several questions about singleton types, but since they are both very closely related, I send them under the same thread.

Q1. Why does # 1 not compile, but # 2 does?

def id(x: Any): x.type = x // #1 def id(x: AnyRef): x.type = x // #2 

Q2. The type is correctly inferred in the case of String , but not in the case of other reference types that I tried. Why is this so?

 scala> id("hello") res3: String = hello scala> id(BigInt(9)) res4: AnyRef = 9 scala> class Foo defined class Foo scala> id(new Foo) res5: AnyRef = Foo@7c5c5601 
+6
source share
2 answers

Singleton types can only refer to AnyRef descendants. See Why String Literals Match Scala Singleton for more details.

An argument to which the id(BigInt(9)) application id(BigInt(9)) cannot be referenced through a stable path, therefore, therefore, it does not have an interesting singleton type.

 scala> id(new {}) res4: AnyRef = $anon$1@7440d1b0 scala> var o = new {}; id(o) o: Object = $anon$1@68207d99 res5: AnyRef = $anon$1@68207d99 scala> def o = new {}; id(o) o: Object res6: AnyRef = $anon$1@2d76343e scala> val o = new {}; id(o) // Third time the charm! o: Object = $anon$1@3806846c res7: o.type = $anon$1@3806846c 
+7
source

I also get the error at # 2 (using Scala 2.9.1.final):

 error: illegal dependent method type def id(x: AnyRef): x.type = x; ^ one error found 

I believe the correct solution is to use make id polymorphic using a type parameter:

 def id[T <: Any](x: T): T = x; 
-1
source

Source: https://habr.com/ru/post/923221/


All Articles