如何在Scala中访问函数参数的字段’arg’

huangapple go评论48阅读模式
英文:

How to access the field 'arg' of a function argument in Scala

问题

我有一个函数:

def func(f: Any => WrappedDataset): WrappedDataset = {
 // 我想在这里做一些类似 `val expr = f.arg.expr` 的操作
}

在 'f' 上没有名为 'arg' 的字段。但是,当我在 func 内部设置断点时,我可以看到我需要的 "expr" 字段在运行时存在。

如何在Scala中访问函数参数的字段’arg’

是否有一种方式,也许使用 Scala 反射,可以将一个 arg 字段内的值提取并保存到 func() 内的一个变量中?

英文:

I have a function:

def func(f: Any => WrappedDataset): WrappedDataset = {
 // I would like to do something like `val expr = f.arg.expr` here
}

There is no such field on 'f' called arg. But when I put a breakpoint inside of func I can see that the field I need "expr" is there at runtime.

如何在Scala中访问函数参数的字段’arg’

Is there some way, perhaps using scala reflect, that I can take the value inside of one of the arg fields and save to a variable inside of func() ?

答案1

得分: 4

也许我误解了你的问题,但在func的主体中并没有"arg"这样的东西。在你的情况下,只有一个可以应用于定义类型参数的函数,想象一下:有人送给你一台意大利面制造机。生面团放进去,出来的是意大利面条。当你拿到这台面条机时,你不能说"好的,让我看看生面团"。现在,你只有一台面条机(函数),稍后一旦你获得了一些生面团(类型为Any的值),你就可以应用它。

如果你需要在func()的主体中知道参数,那么你需要将其作为参数传递:

def func(f: Any => WrappedDataset, arg: Any): WrappedDataset
英文:

Perhaps I misunderstand your question, but there's no such thing as "arg" as far as the body of func is concerned. There's only a function that can be applied to an argument of the defined type, in your case Any.

Think of it like this: someone gifts you a pasta maker. Raw pasta goes in, spaghetti come out. When you're handed this pasta maker, you can't say "okay let me look at the raw pasta". For now, all you have is a pasta maker (function), and later once you obtain some raw pasta (value of type Any), you will be able to apply it.

If you need to know the argument in the body of func(), then you need to make it a parameter:

def func(f: Any => WrappedDataset, arg: Any): WrappedDataset

huangapple
  • 本文由 发表于 2023年6月8日 17:53:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定