Scala UpperBound and LowerBound concept

后端 未结 1 1389
暗喜
暗喜 2021-02-06 05:29

Below is the code I am trying to run:

class Student {
  def printDetails = println(\"I am a student\")
  def printSomeOtherDetails = println(\"I love Studying\")         


        
相关标签:
1条回答
  • 2021-02-06 06:00

    Your understanding is not wrong, but you haven't followed through the consequences.

    Specifically, all parameters have, in effect, an upper bound of Object if no explicit upperr bound is provided. This is happening in the case of the method printStudentDetails in your type MyGenericClassforLowerBound. That is, a value of type Object could be legally passed as the parameter to this method. But type Object does not define the methods printDetails and printSomeOtherDetails - hence the error.

    To make the method compile, you would need to also provide a suitable upper bound (similar to MyGenericClassforUpperBound), eg:

    def printStudentDetails[S >: ComputerScienceStudent <: Student](student: S) = { ...
    

    It should be noted in this case, however, that the lower bound effectively becomes redundant, because any parameter that subclasses Student can be passed in successfully because it can be treated as of type Student, satisfying teh upper bound - so even InformationTechnologyStudent and subclasses of ComputerScienceStudent can be passed into it successfully. This sort of construct is more useful when you might be passed in values mixing in types from two different hierarchies.

    0 讨论(0)
提交回复
热议问题