Black monkey house: Scala view definition

1 Overview

In the previous section, we take a look at an example of a multi-sector

class Pair[T <: Comparable[T]]

Unfortunately, if we try a new Pair (4,2), the compiler will complain that Int subtype is not Comparable [Int] is. And Java.lang.Integer different packaging types, Scala's type Int and does not implement Comparable. However, RichInt realized Comparable [Int], as well as a conversion from Int to RichInt the hermit, hermit converted back we will explain

The solution is to use the "View definition (view bound)", like this:

class Pair[T <% Comparable[T]]

<% Relationship means T can be converted into a hermit Comparable [T]
However, the definition Scala view of the upcoming stage of history, open -future option if you then compile time, using the view definition will be warned compiler. You can use the "type constraint (type constraint)" defines an alternate view, like this

class Pair[T](val first:T,val second:T)(implicit ev:T=> Comparable[T]){
   def smaller = if (first.comparaTo(second) <0 ) first else second
}

2, practical operation

In Scala, a mark if you want a generic implicitly converted to another generic, you can use: [T <% Comparable [T]], due to the Int Scala's type does not implement the Comparable interface, so we need to Int type implicit type conversion to RichInt

class Pair5[T <% Comparable[T]](val first: T, val second: T) {
  def smaller = if (first.compareTo(second) < 0) first else second
  override def toString = "(" + first + "," + second + ")"
}

object Main5 extends App {
  val p = new Pair5(4, 2)
  println(p.smaller)
}

Reproduced in: https: //www.jianshu.com/p/5d835a086976

Guess you like

Origin blog.csdn.net/weixin_34389926/article/details/91182525