Scala lower type bound'是对方法参数

时间:2016-01-06 15:32:00

标签: scala

在Scala中,为什么在方法类型参数上设置较低的类型边界不会对方法参数强制执行“超类型”限制?

object TypeBounds extends App {
  class MotorVehicle
  class Truck extends MotorVehicle
  class Car extends MotorVehicle
  class Saloon extends Car
  class HatchBackSaloon extends Saloon

  def lowerTypeBound[C >: Car](c: C): C = c

  def upperTypeBound[C <: Car](c: C): C = c

  // Works. HatchBackSaloon is a sub class of Car
  println(upperTypeBound(new HatchBackSaloon())) 

  // as expected doesn't compile. Truck is not a subclass of Car    
  println(upperTypeBound( new Truck()))  

  // Compiles and runs, but why ?  HatchBackSaloon is not a super class of Car.
  println(lowerTypeBound(new HatchBackSaloon())) 

}

1 个答案:

答案 0 :(得分:6)

您的示例中的

C具体化为Car,而不是HatchbackSaloon

看起来像def lowerTypeBound(c: Car): Car的函数可以接受HatchbackSaloon类型的参数,这并不奇怪,对吗?

尝试这样的事情:

val result: HatchBackSaloon = lowerTypeBound(new HatchBackSaloon)

这将无法编译,因为它需要CHatchbackSaloon,而Car不是val result: MotorVehicle = lowerTypeBound(new HatchbackSaloon) 的超类。但这会奏效:

C

因为此处MotorVehicle[main] authc.usernameParam = j_username authc.passwordParam = j_password authc.failureKeyAttribute = shiroLoginFailure jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm jdbcRealm.permissionsLookupEnabled = true jdbcRealm.authenticationQuery = "SELECT password FROM user WHERE username = ?" jdbcRealm.userRolesQuery = "SELECT role FROM user WHERE username = ?" ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds.serverName = localhost ds.user = root ds.password = password ds.databaseName = database jdbcRealm.dataSource = $ds # Use Built-in Chache Manager builtInCacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager securityManager.cacheManager = $builtInCacheManager securityManager.realms = $jdbcRealm [users] [roles] [urls] /* = authcBasic ,而且允许这样做。