3 回答
TA贡献1853条经验 获得超18个赞
case class Foo[A](a:A) { // 'A' can be substituted with any type // getStringLength can only be used if this is a Foo[String] def getStringLength(implicit evidence: A =:= String) = a.length}
evidence
A
String
A
String
A
String
a.length
scala> Foo("blah").getStringLength res6: Int = 4
Foo
String
:
scala> Foo(123).getStringLength<console>:9: error: could not find implicit value for parameter evidence: =:=[Int,String]
getStringLength
A
Foo
getStringLength
Foo[String]
<:<
<%<
A =:= B
意思是A一定就是B A <:< B
表示A必须是B的子类型(类似于 简约
类型约束 <:
)A <%< B
意思是A必须是 可见
作为B,可能通过隐式转换(类似于简单类型约束)。 <%
)
增编
List.sumInts
List
List[Int]
List
sumInts
List[Int]
TA贡献2021条经验 获得超8个赞
def getStringLength(implicit evidence: A =:= String)
A =:= String
=:=[A, String]
=:=
val a: Tuple2[Int, String] = (1, "one")
val a: Int Tuple2 String = (1, "one")
.
()
TA贡献1804条经验 获得超2个赞
class Pair[T](val first: T, val second: T)
smaller
def smaller = if (first < second) first else second
T
class Pair[T <: Ordered[T]](val first: T, val second: T)
T
smaller
def smaller(implicit ev: T <:< Ordered[T]) = if (first < second) first else second
Pair[File]
, 只要你不打电话 smaller
Option
orNull
Option[Int]
orNull
Option[String]
Option[Int]
orNull
Some(42).orNull
error: Cannot prove that Null <:< Int
添加回答
举报