scala中泛型和隐式转化

隐式转化

边写边译模式中:

new Person[Int](15,18).max()
class Data(number: Int){
 def show(): Int ={
   print("1"+" "+number)
   2
 }
}
implicit def show(num:Int) = new Data(num)
1.show

如果下面这句代码,就会报错,下面这个代码就起到了隐式转换的作用,

implicit def show(num:Int) = new Data(num)

泛型的使用

边写边译模式中:

class Person[M<%Comparable[M]](var x:M,var y:M){
  def max(): Int ={
    x.compareTo(y)
  }
}
new Person[Int](15,18).max()

其中%起到了隐式转化的作用

本来代码是这样的:

class Person[M<:Comparable[M]](var x:M,var y:M){
  def max(): Int ={
    x.compareTo(y)
  }
}
new Person[Int](15,18).max()

但是发现这里会报错,原因是Comparable给泛型一个上限类,所在类需要继承Comparable,

但是scala中Int没有继承该类,将Int换成Integer或String就行

new Person[Int](15,18).max()
class Data(number: Int){
def show(): Int ={
print("1"+" "+number)
2
}
}
implicit def show(num:Int) = new Data(num)
1.show

猜你喜欢

转载自www.cnblogs.com/han-guang-xue/p/10026548.html