2012-08-16 3 views
0

가능한 중복은 :스칼라 유형 삭제?

scala> var s = new Stack()push(1) 
s: scalatest.Stack[Int] = 1 

scala> s match { case s : Stack[String] => print("Hello")} 
<console>:12: warning: non variable type-argument String in type pattern scalatest.Stack[String] is unchecked since it is eliminated by erasure 
       s match { case s : Stack[String] => print("Hello") 
} 

스택 http://www.scala-lang.org/node/129에서 가져온 클래스 :


How do I get around type erasure on Scala? Or, why can't I get the type parameter of my collections?

는 다음 코드를 실행. -unchecked 플래그없이이 코드를 실행하면 "Hello"가 인쇄됩니다. 왜 그런 경우입니까?

+0

컴파일러에서 문제가 있음을 알리고 그게 무엇입니까? 왜 여기서 물어 보는거야? –

답변

2

s과 일치하는 것이 Stack[String] 인 문제입니다. s 유형 Stack의 경우 런타임 동안, 결정하는 것이 가능하지만 때문에 자바의 type erasure의는 s 그래서 어떤 문제 유형 매개 변수, 그것이 case 표현과 일치 도착했습니다 유형 Stack[String], Stack[Int] 등으로없는 경우를 결정하는 것은 불가능합니다 . 이것이 스칼라가 경고를 내리는 이유입니다.

s match { case s : Stack[_] => print("Hello")} 

(경고없이 컴파일 됨)과 일치하는 경우와 같습니다.


편집 :가 (너무 Java 용) 해결 방법은 더 이상 유형 매개 변수가없는 특정 클래스를 만드는 것입니다. 예를 들면 :

import scala.collection.mutable.Stack; 

object Test extends App { 
    class MyStack extends Stack[Int]; 
    class MyOtherStack extends Stack[String]; 

    val s: Stack[_] = new MyStack().push(1); 

    s match { 
    case s : MyOtherStack => print("Hello String"); 
    case s : MyStack => print("Hello Int"); 
    } 
} 

그것은 그들의 방법은 새로운 객체를 생성하고이 우리의 특정 서브 클래스의 인스턴스가 될 수 없기 때문에, 불변의 컨테이너를 사용할 수없는 단점이있다.

+0

아, 그래 ... 제네릭이 스칼라에서 구체화되지 않았다. – Bober02

관련 문제