简体   繁体   中英

Turn a method call into a () => T function in Scala

I have a method which looks the following:

def myMethod[T](klazz:Class[T]):Z

I want to create a Map of type Int => () => Z so that in my code, I can look on the map to generate only the Z s I need.

If I do the following, however:

Map( 0 -> myMethod(classOf[String]) _ , 1 -> myMethod(classOf[StringBuilder]))

how can I avoid writing () => myMethod(classOf[String]) ?

Why not simply change myMethod so that it returns a function?

def myMethod( clazz: Class[_]): () => Z = {
  { () => /* put the body of the old myMethod here */ }
}

Then you can do:

Map( 0 -> myMethod(classOf[String]) , 1 -> myMethod(classOf[StringBuilder]))

Another way to do this is with a custom associator:

implicit class LazyMapArrow[K](val self: K) extends AnyVal {
  def ~>[V](other: => V): (K, () => V) = (self, () => other)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM