scala - What's the rule to implement an method in trait? -
I have defined an attribute:
attribute A {def hello (name: someone Also): any one} Then apply it to a class X:
class X one {def hello (name: any ) Expands: Any = {}} It has been compiled after which I change the type of return in the subclass:
in class X The extension is {def hello (name: any): string = "hello"} also compiled Change the parameter type:
square X extends a {def hello (name: string): any = {}} it does not compile This time, the error is:
Error: Class X must be intact, because the type of method is in Hello (name: any) None is defined (note that None matches string: The class string in the package string is a subclass of class, in the package scal E, but the method parameter types match exactly.) It seems that the parameters must match exactly but the return type can be a subtype of the sub-class?
Update: @ Mik378, thanks for your reply, but why the following examples can not work? I think it does not break Liskov:
attribute A {def hello (name: string): any square X one {def hello (name: any) extends: no Also = {}}
This is exactly like Java, to keep you Can not override a method with a more accurate parameter In fact, if your code is related to the A type, under the hood X refers to type a Accordingly, you can give anyone you want , but B only String allow. Therefore = & gt; Boom Logically, with a single argument, a more accurate return type is allowed as it is in case of any code related to the A class , will cover. You can see those parts:
and
UPDATE ------------ Specialty A {def hello (name: string): Any square X expands a {def hello (name: any): any = {}} / code>
This will act as a full overloading, not overriding.
Comments
Post a Comment