scala中的Type使用

时间:2023-03-08 22:23:48
scala中的Type使用
trait Base {
val name: String
} case class S(
name: String,
age: Int
) extends Base case class F(
name: String,
tel: Long
) extends Base case class Info[T <: Base](
b: T,
time: String
) object Test extends App {
override def main(String args): Unit = {
val i = Info(F("Jim", 23212341), "15:15:30") i match {
case info @ Info(b: F, time) =>
println(s"F info: $info") case info @ Info(b: S, time) =>
println(s"S info: $info") }
}
}

一、scala 使用 generic 通用类型如何做模式匹配

上述的case class Info在模式匹配时,需要使用

           case info @ Info(b: S, time) =>

代替传统的

           case info:Info =>

如果用下面的,编译时会有警报

non variable type-argument String in type pattern String => _ is unchecked since it is eliminated by erasure

二、scala 如何返回某个基类trait的subClass or subType

还是以上面的例子讲解

如果我想返回F或者S,可以使用

def getSub[T <: Base](b: Base): T = {
b.asInstanceOf[T]
}

但是这里要注意,如果入参b不是我们想要的T类型,编译会有error

三、scala中的trait中引入一个superClass —— subClass,如何在这个trait中规定返回subClass的类型

trait GoBase {
type BB <: Base val b: BB def getBase(): BB = b } class Go1 {
override type BB = F val b = F("Tom", 9939122)
} object Test1 {
val go = new Go1
val b = go.getBase
println(b.toString) // F("Tom", 9939122)
}

四、scala中怎么在collection中获得类型参数

详细参考 https://*.com/questions/1094173/how-do-i-get-around-type-erasure-on-scala-or-why-cant-i-get-the-type-paramete

使用scala.reflect.Manifest API