Scala:要求函数参数是某个类的成员? [英] Scala: require that a function argument is a member of some class?
本文介绍了Scala:要求函数参数是某个类的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想做类似的事情
class A {
def f1: Unit = ...
def f2: Unit = ...
}
def foo(f: => Unit) {
(new A).f // ???
}
其中 f 应该是 A 类的成员函数.我相信标准的解决方案是
where f is supposed to be a member function of class A. I believe the standard solution is
def foo(f: A => Unit) {
f(new A)
}
并以这种方式使用它
foo(_.f1)
foo(_.f2)
但是现在我可以传入具有此签名的任意函数,这可能不是我们想要的.有没有办法确保,我传入的函数是某个类的成员?
But now I can pass in an arbitrary function that has this signature, which may be not desired. Is there anyway to ensure that, the function I pass in is a member of certain class?
推荐答案
好吧,如果你不介意一些扭曲,你可以使用函数毕竟是一个类的事实......
Well, if you don't mind a few contortions, you can use the fact that a function IS a class after all...
// abstract class MyIntToString extends (Int => String) // declare here if you want
// to use from different classes
// EDIT: f1 and f2 are now val instead of def as per comment below
// by @Régis Jean-Gilles
class A {
abstract class MyIntToString private[A]() extends (Int => String)
// if MyIntToString is declared here
// with a constructor private to the enclosing class
// you can ensure it's used only within A (credit goes to @AlexeyRomanov
// for his comment below)
val f1 = new MyIntToString {
def apply(i: Int) = i.toString + " f1"
}
val f2= new MyIntToString {
def apply(i: Int) = i.toString + " f2"
}
}
def foo(f: A#MyIntToString) = f(42) // f: MyIntToString if MyIntToString not nested in A
val a = A
现在你可以:
scala> foo((new A).f1)
res1: String = 42 f1
scala> foo((new A).f2)
res2: String = 42 f2
但 foo 不会接受 Int =>字符串
签名
but foo will not accept Int => String
signatures
scala> val itos = (i:Int) => i.toString
itos: Int => String = <function1>
scala> foo(itos)
<console>:11: error: type mismatch;
found : Int => String
required: MyIntToString
foo(itos)
^
这篇关于Scala:要求函数参数是某个类的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文