1
나는이 유형이없는 사용 스칼라의 Something[X]
에 Something[Any]
변환하는 기능 :어떻게 사용 스칼라에서 출연진과 asInstanceOf의 결과를 반환하는 무형의
import shapeless._
import shapeless.syntax.typeable._
def doCast[T: Typeable](v: Vector[Any]): T = v.cast[T].get
가 지금은 인덱스 목록에 액세스 할을 :
val a = Vector[Any](1,2,3);
println(doCast[Vector[Int]](a)(1))
그러나 이것은 예외가 발생합니다 :
/path/to/Test.scala:12: error: type mismatch;
found : Int(1)
required: shapeless.Typeable[Vector[Any]]
println(doCast[Vector[Int]](a)(1))
^
one error found
을 내가 처음 변수에이 결과를 할당하는 경우
그러나, 그것은 제대로 2
인쇄 :
val a = Vector[Any](1,2,3);
val c = doCast[Vector[Int]](a)
println(c(1))
을 마찬가지로, 내가 asInstanceOf
를 사용하여 결과를 캐스팅하는 경우 제대로 작동 :
val a = Vector[Any](1,2,3);
println(doCast[Vector[Int]](a).asInstanceOf[Vector[Int]](1));
수 나는 색인 결과를 반환하는 함수를 생성합니까?
나는 그렇게하려고했으나 내 시도는 작동하지 않았다 :
/path/to/Test.scala:10: error: diverging implicit expansion for type shapeless.Typeable[T]
starting with method inrTypeable in object Typeable
def doCast2[T](v: Vector[Any]): T = doCast(v).asInstanceOf[T]
^
one error found
및
def doCast2[T](v: Vector[Any]): T = doCast[T](v).asInstanceOf[T]
이 오류를 제공합니다 :
def doCast2[T](v: Vector[Any]): T = doCast(v).asInstanceOf[T]
이 오류를 제공
/path/to/Test.scala:10: error:
class type required but T found
def doCast2[T](v: Vector[Any]): T = doCast[T](v).asInstanceOf[T]
^
one error found