What is the rule for implementing a method in value?

I have identified the symptom:

trait A {
   def hello(name:Any):Any
}

Then define the class X to implement it:

class X extends A {
  def hello(name:Any): Any = {}
}

Compiled. Then I change the return type in the subclass:

class X extends A {
  def hello(name:Any): String = "hello"
}

It is also compiled. Then change the parameter type:

class X extends A {
  def hello(name:String): Any = {}
}

It cannot compile this time, error:

error: class X needs to be abstract, since method hello in trait A of type (name: Any)
Any is not defined
(Note that Any does not match String: class String in package lang is a subclass 
of class Any in package scala, but method parameter types must match exactly.)

It seems that the parameter should exactly match, but the return type may be a subtype in the subclass?


Update: @ Mik378, thanks for your answer, but why can't the following example work? I think this will not break Liskov:

trait A {
   def hello(name:String):Any
}

class X extends A {
   def hello(name:Any): Any = {}
}
+4
source share
3 answers

Java, , .

, , A, X . A, Any, , B String. = > BOOM

, , , , , , A.

: http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Covariant_method_return_type

http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Contravariant_method_argument_type

UPDATE ----------------

trait A {
   def hello(name:String):Any
}

class X extends A {
   def hello(name:Any): Any = {}
}

, .

+6

Scala , :

class X extends A {
  def hello(name:String) = "String"
  def hello(name:Any) = "Any"
}

Java ( - , ).

, , . .

Scala Java - . , , :

class X extends A {
  def hello: Any = "World"
  def hello: String = "Hello"
  def doSomething = {
    println(hello.toString) // which hello do we call???
  }
}

- , .

JVM - JVM . Java Scala , Java Scala.

+2

, X.hello, A.hello, X.hello A.hello () X.hello A.hello ().

,

class A 
class A' extends A
class B 
class B' extends B

f :: A' -> B
g :: A  -> B'

: " f g y=f(x) ?

y B, x A'

y=f(x) , y B, x A'

g(x) - , x A' ( , A)

y=g(x) - , g(x) B' ( , B)

, y B (.. B), , y B. - .

(I just remember that this is one direction at the entrance, the other is at the exit, and try it ... it becomes obvious if you think about it).

+1
source

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


All Articles