3 回答

TA貢獻1853條經(jīng)驗 獲得超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,可能通過隱式轉(zhuǎn)換(類似于簡單類型約束)。 <%
)
增編
List.sumInts
List
List[Int]
List
sumInts
List[Int]

TA貢獻2021條經(jīng)驗 獲得超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條經(jīng)驗 獲得超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
添加回答
舉報