小编Syl*_*cka的帖子

Scala 转换为泛型类型

我对泛型类型感到困惑。我希望它2.asInstanceOf[A]被转换为 type A,同时,它被转换为Int. 除此之外,输入是java.lang.Long而输出是一个列表Int(根据定义,输入和输出应该是相同的类型)。这是为什么?

def whatever[A](x: A): List[A] = {
  val two = 2.asInstanceOf[A]
  val l = List(1.asInstanceOf[A],2.asInstanceOf[A])

  println(f"Input type inside the function for 15L: ${x.getClass}")
  println(f"The class of two: ${two.getClass}, the value of two: $two")
  println(f"The class of the first element of l: ${l.head.getClass}, first element value: ${l.head}")
  l
}

println(f"Returned from whatever function: ${whatever(15L)}")

Run Code Online (Sandbox Code Playgroud)

输出:

Input type inside the function for 15L: class java.lang.Long
The class of two: class …
Run Code Online (Sandbox Code Playgroud)

boxing casting scala type-erasure

4
推荐指数
1
解决办法
406
查看次数

标签 统计

boxing ×1

casting ×1

scala ×1

type-erasure ×1