2017-04-24 6 views
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 

답변

1

문제는 desugaring 후 doCast의 실제 서명에서 변환되는 것 같다 :이

doCast[Vector[Int]](a)(1) 

처럼 호출 할 때

def doCast[T: Typeable](v: Vector[Any]): T 

그래서

def doCast[T](v: Vector[Any])(implicit ev1: Typeable[T]): T 

로 Typeable [T]의 위치에서 1을 전달 중입니다.

doCast[Vector[Int]](a)(implicitly)(1) 

또는 doCast

후 벡터에 대한 별도의 발을 사용

쉬운 솔루션을 직접 매개 변수를 지정하는 것입니다