Confusion in understanding scala

I read the Demystifying Scala Type System , on the 17th slide there is a fragment:

class Test[+A] {
  def test[B >: A](b: B): String = b.toString
}

The slide says that the test method will accept type A or any super type A. But it seems that I can pass any type for testing.

vat t = new Test[Int]
t.test("foo")
t.test(List(1, 2, 3))

I have the same confusion when I read Programming in Scala.

+4
source share
2 answers

It is important to remember that Anythis is a super type of any type, i.e.

Any >: A

In particular, suppose that

val t = new Test[Int]

That A Int. Now we call

t.test("foo")

"foo" String, Any , , , test[B >: A](b : B) b, "foo" b Any.

,

class Test[+A](a : A) {
  def test[B >: A](b : B) : (A,B) = (a,b)
}

,

val t = new Test(3)
val x = t.test("foo")

x: (Int, Any) = (3,foo)

, , Scala Any, A b. , Any Int String (. http://www.scala-lang.org/old/node/128), - , ,

val s = new Test(Nil)
val y = s.test("foo")
val z = s.test(List(1))

y: (scala.collection.immutable.Nil.type, java.io.Serializable) = (List(),foo)
z: (scala.collection.immutable.Nil.type, List[Int]) = (List(),List(1))

, A

scala> val a = new Test(new AnyRef())
a: Test[java.lang.Object] = Test@6771a12

scala> a.test("foo")
res6: (java.lang.Object, java.lang.Object) = (java.lang.Object@78b99f12,foo)

, , ? , "" "" , , ., , http://docs.scala-lang.org/tutorials/tour/lower-type-bounds.html , () A , " " A. ( , , , , , , , )

+6

- Any. , , .

- B,

class Test[+A] {
  def test[B >: A](b: B): B = b
}


class A

class B extends A

val test = new Test[B]

val t = test.test("test")

, . , .

, , A, . - Function1 [-A, + B]. def def (b: A)..... :

A A b def test (b: A): String = b.toString

, , . , .

class C

class CCC extends C

def test[B >: A](b: B)(implicit ev: B =:= C): B = b

val test = new Test[CCC]

test.test(new C)//ok

test.test("123")//compilation error
0

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


All Articles