는 스칼라에서이 같은 방법 정의가 말 T의 유형에 따라?스칼라 패턴
Function1
대신에 다시 작성해야하고 패턴 일치가 필요합니까?
내가 해봤 다음하지만 때문에 형의 삭제에 작동하지 않습니다 어쩌면 추상적 인 유형
class A {
def x(fn: A => Unit): Unit = fn(this)
}
class B {
def y(fn: B => Unit): Unit = fn(this)
}
def handle[T](fn: Function1[T, Unit]): Unit = {
fn match {
case fnA: Function1[A, Unit] =>
new A().x(fnA)
case fnB: Function1[B, Unit] =>
new B().y(fnB)
}
}
를?
예상 출력을 인쇄import scala.reflect.runtime.universe._
class A {
def x(fn: A => Unit): Unit = fn(this)
override def toString = "A"
}
class B {
def y(fn: B => Unit): Unit = fn(this)
override def toString = "B"
}
def handle[T : TypeTag](fn: Function1[T, Unit]): Unit = typeOf[T] match {
case t if t =:= typeOf[A] => new A().x(fn.asInstanceOf[Function1[A, Unit]])
case t if t =:= typeOf[B] => new B().y(fn.asInstanceOf[Function1[B, Unit]])
}
handle[A] { a: A =>
println("It's " + a)
}
handle[B] { b: B =>
println("It's " + b)
}
가 :
'handle'의 서명을 변경하는 것이 좋습니까? 그리고 A와 B를 바꿀까? – Beryllium