在Scala中的模式匹配的match子句中使用对象

时间:2019-06-23 17:03:56

标签: scala

我有这样的代码:

Widget build(BuildContext context) {
 return Scaffold(
  appBar: AppBar(
    title: Text('Social App'),
    actions: <Widget>[
      Padding(
        padding: const EdgeInsets.only(right: 10.0),
        child: IconButton(icon: Icon(Icons.add), onPressed: (){})
      ),
    ],
  ),

body: Column(
    children: <Widget>[
      Flexible(
        flex: 0,
        child: Card(
          child: Form(
            key: formKey,
              child: Flex(
              direction: Axis.vertical,
            children: <Widget>[
              ListTile(
                leading: Icon(Icons.subject),
                title: TextFormField(
                  initialValue: '',
                  onSaved: (val) => board.subject = val,
                  validator: (val) => val == "" ? val: null,
                ),
              ),
              ListTile(
                leading: Icon(Icons.message),
                title: TextFormField(
                  initialValue: '',
                  onSaved: (val) => board.body = val,
                  validator: (val) => val == "" ? val: null,
                ),
              ),
              FloatingActionButton(
                child: Text('post'),
                backgroundColor: Colors.pink,
                onPressed: (){
                  handleSubmit();
                },
              ),
            ],
        ),
      ),
      ),
  ),

如何将match子句中someOtherObject.subObjects()。size的值分配给case语句中的size变量

我必须做:

val s = someOtherObject.subObjects().size match {
  case size > 0 => "Size is greater than 0"
  case _ => "Size is less than 0"
}

2 个答案:

答案 0 :(得分:2)

val s = size match {
  case x if x > 0 => ("Size is greater than 0", x)
  case x @ _ => ("Size is less than 0", x)
}

是元组(字符串,整数)

s._1将是字符串消息

s._2将是size的值。

答案 1 :(得分:0)

您可以给该变量命名,然后将其返回,如下所示:

val s = someOtherObject.subObjects().size match {
  case size if size > 0 => size
  case size @ _ => size
}

或者您可以简单地使用if表达式:

val size = someOtherObject.subObjects().size

val result = if(size > 0) {
  // Size is greater than zero
  size
} else {
  // Size is less than or equal to zero
  size
}
相关问题