2017-04-22 3 views
0

scala와 같은 함수 주위에 문서 래퍼를 만들려고하므로 다음과 같이 래퍼가 포함 된 함수 문서를 쿼리 할 수 ​​있습니다.형식이 명시 적으로 지정되지 않은 한 스칼라 형식 유추가 형식 경계에서 작동하지 않습니다.

val xy = x1 compose y1 

cmd3.sc:1: inferred type arguments [Nothing,cmd3Wrapper.this.cmd1.cmd0.wrapper.WrappedFunction1[String,String]] do not conform to method compose's type parameter bounds [C,T <: cmd3Wrapper.this.cmd1.cmd0.wrapper.WrappedFunction1[String,C]] 
val xy = x1 compose y1 
      ^cmd3.sc:1: type mismatch; 
found : cmd3Wrapper.this.cmd1.cmd0.wrapper.WrappedFunction1[String,String] 
required: T 
val xy = x1 compose y1 
        ^
Compilation Failed 
: 나는이 두 가지를 작성할 때 나는 유형 추론 위선적 인 말투, 그러나

import Wrapper._ 
val x : String => String = _.toLowerCase 
val y : String => String = _.toUpperCase 
val x1 = x.wrap("a function for lowercasing") 
val y1 = y.wrap("a function for uppercasing") 

println(x1("LOL")) // lol 
println(x1.doc) // a function for lowercasing 

: 여기

trait WrappedFunction1[A, B] { 
    def f : Function1[A, B] 
    def doc: String 
    def apply(x:A):B = f(x) 
    def compose[C, T <:WrappedFunction1[B, C]](that:T):WrappedFunction1[A, C] = 
    new Wrapper[A, C](this.f andThen that.f, this.doc + " composed with " + that.doc) 
} 

class Wrapper[A, B](f1:Function1[A, B], sos:String) extends WrappedFunction1[A, B] { 
    val f = f1 
    val doc = sos 
} 

object Wrapper { 
    implicit class Wrap[A, B](f1:Function1[A, B]) { 
    def wrap(sos:String):WrappedFunction1[A, B] = new Wrapper(f1, sos) 
    } 
} 

내가이를 사용하십시오 방법

내가 명시 적으로 유형을 명시하는 경우 그 작동 작곡 :

val xy = x1 compose[String, WrappedFunction1[String, String]] y1 

이 거기 어딘가에 내가 잘못거야? 더 좋은 방법이 있습니까? (나는 타입 테라클을 시도했으나 아마도 하나의 타입 매개 변수, 다른 대수 데이터 타입을 가진 형질에 대해 정의 된 것 같다.)

답변

1

이 문제는 스칼라 유형 유추의 세부 사항에있다. T을 먼저 추론 한 다음 C을 유추 할 수 없습니다. 대신에 한 번에 둘 다 추론해야합니다. 이 T를 확인할 수 있습니다 that: T에서

하지만 C은 매개 변수 유형에 언급되지 않은, 그래서 Nothing이 할당 만 다음 단계에 컴파일러 고지가 맞지 않습니다. 그래서 수정은 단순히

def compose[C, T <:WrappedFunction1[B, C]](that: T with WrappedFunction1[B, C]) 

더 좋은 방법으로 유형을 변경

def compose[C](that: WrappedFunction1[B, C]) 

이 이미 WrappedFunction1[B, C]의 하위 유형을 통과 할 수 있기 때문에

입니다!