如何检查两个布尔值?值在Kotlin中为真

时间:2019-11-21 11:58:23

标签: kotlin

示例代码:

val todayCount = keyValue.value.filter {
        val after = it.expectedArrivalDate?.after(today)
        val before = it.expectedArrivalDate?.before(tomorrow)
        after != null && before != null && after && before
    }.size

如果it.expectedArrivalDate不是nullable,我会写这样的东西:

val todayCount = keyValue.value.filter {
    it.expectedArrivalDate.after(today) && it.expectedArrivalDate.before(tomorrow)
}.size

是否可以简化我的代码?

5 个答案:

答案 0 :(得分:4)

扩展功能或Elvis运算符的替代方法只是== true

在Java中,==比较引用,这很危险,因为对于任何新的布尔实例而言,它都会失败。但是在Kotlin中,==使用.equals()比较值(在进行了必要的空检查之后),因此可以很好地处理这种情况。

所以您的代码可能是:

val todayCount = keyValue.value.filter {
    it.expectedArrivalDate?.after(today) == true
    && it.expectedArrivalDate?.before(tomorrow) == true
}.size

类似地,如果您希望null算作true,则可以使用!= false

可以说这不是最优雅的解决方案,但它可能是最简单的!

答案 1 :(得分:2)

您可以创建extension functions来简化该检查。

假设expectedArrivalDate的类型为Date,则可以为可空的Date类型after添加beforeDate?函数,如果日期类型为{实例为null,或者如果不为null,则调用原始的after / before函数:

fun Date?.after(anotherDate: Date): Boolean = this?.after(anotherDate) ?: false
fun Date?.before(anotherDate: Date): Boolean = this?.before(anotherDate) ?: false

并保持您的代码不变:

val todayCount = keyValue.value.filter {
    it.expectedArrivalDate.after(today) && it.expectedArrivalDate.before(tomorrow)
}.size

或者您可以直接在代码中直接使用实现:

val todayCount = keyValue.value.filter {
    (it.expectedArrivalDate?.after(today) ?: false) && (it.expectedArrivalDate?.before(tomorrow) ?: false)
}.size

答案 2 :(得分:0)

考虑使用?:使用variable re-declaration

  

变量重新声明(和阴影)。

fun leftPad(value: String, length: Int? = null, char: Char? = null): String {
    val length = length ?: 4
    val char = char ?: ' '

答案 3 :(得分:0)

不确定这是否可以简化,但是作为另一种选择,您可以:

val todayCount = keyValue.value.filter {
    it.expectedArrivalDate?.takeIf{d -> d.after(today)}?.takeIf{d -> d.before(tomorrow)}?.let{true}?:false
}.size

答案 4 :(得分:0)

不带扩展功能的替代方法:由于所有比较都基于同一个字段,因此您可以在删除所有空值的同时实际映射它。

下面是一个带有伪旅行类的示例代码,因此您可以看到它进行了编译:


import sys
sys.path.insert(1, 'path')
import pandas as pandas
import matplotlib.pyplot as plt
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Input, Output
import forex_factory_calendar_scraper as ffcs
import economic_calendar_reader as ecr 
import time


#  Fuctions for RangeSlider. Dash does not support DateTime objects
def unixTimeMillis(dt):
    ''' Convert datetime to unix timestamp '''
    return int(time.mktime(dt.timetuple()))

def unixToDatetime(unix):
    ''' Convert unix timestamp to datetime. '''
    return pd.to_datetime(unix,unit='s')

def getMarks(start, end, daterange, Nth=50000):
    ''' Returns the marks for labeling. 
        Every Nth value will be used.
    '''
    result = {}
    for i, date in enumerate(daterange):
        if(i%Nth == 1):
            # Append value to dict
            result[unixTimeMillis(date)] = str(date.strftime('%Y-%m-%d'))
    return result



app = dash.Dash(__name__)

#  Importing data
ffcs.get_economic_calendar("calendar.php?month=dec.2019","calendar.php?month=dec.2019")
calendar = ecr.read_economic_calendar()

#calendar = calendar.loc[calendar.Currency == 'EUR']
available_currencies = calendar.Currency.unique()

app.layout = html.Div([
    html.Div([

        html.Div([
            dcc.Dropdown(
                id='currency1',
                options=[{'label': i, 'value': i} for i in available_currencies],
                value='EUR'
            )
        ],
        style={'width': '48%', 'display': 'inline-block'}),

        html.Div([
            dcc.Dropdown(
                id='currency2',
                options=[{'label': i, 'value': i} for i in available_currencies],
                value='USD'
            )
        ],style={'width': '48%', 'float': 'right', 'display': 'inline-block'}),

        html.Div([
            dcc.Dropdown(
                id='events1',

            )
        ],
        style={'width': '48%', 'display': 'inline-block'}),

        html.Div([
            dcc.Dropdown(
                id='events2',

            )
        ],style={'width': '48%', 'float': 'right', 'display': 'inline-block'}),

        html.Div([
            dcc.RadioItems(
                id='disp_col1',
                options=[
                {'label': 'Actual', 'value':'Actual'},
                {'label': 'Surprise %', 'value':'Surprise_Pct'}
                ],
                value='Actual'
            )
        ],
        style={'width': '48%', 'display': 'inline-block'}),

        html.Div([
            dcc.RadioItems(
                id='disp_col2',
                options=[
                {'label': 'Actual', 'value':'Actual'},
                {'label': 'Surprise %', 'value':'Surprise_Pct'}
                ],
                value='Actual'
            )
        ],style={'width': '48%', 'float': 'right', 'display': 'inline-block'}),
    ]),
    html.Div([
        dcc.Graph(id='surprice_pct-ts1'),
    ],style={'width': '48%', 'display': 'inline-block'}),

    html.Div([
        dcc.Graph(id='surprice_pct-ts2'),
    ],style={'width': '48%', 'float': 'right', 'display': 'inline-block'}),

    html.Div([
        html.Div([
            dcc.RangeSlider(
                id='year_slider',
                min = unixTimeMillis(calendar.Date.min()),
                max = unixTimeMillis(calendar.Date.max()),
                value = [unixTimeMillis(calendar.Date.min()),
                         unixTimeMillis(calendar.Date.max())]
                #marks=getMarks(calendar.Date.min(),
                #            calendar.Date.max(), calendar.Date)
            )
        ],style={'width': '70%', 'display': 'inline-block'})
    ],style={'width': '100%', 'text-align': 'center'})
])

#   Left Graph ------------------------------------------------------------->>
@app.callback(
     dash.dependencies.Output('surprice_pct-ts1', 'figure'),
    [dash.dependencies.Input('currency1', 'value'),
     dash.dependencies.Input('events1', 'value'),
     dash.dependencies.Input('disp_col1', 'value'),
     dash.dependencies.Input('year_slider', 'value')])

def update_ts1(currency1,events1, disp_col1, year_slider):

    output = calendar[calendar.Currency == currency1]
    output = output[output.Event == events1]


    data = []
    trace_data = go.Bar(x=list(output.Date),
                        y=list(output[disp_col1]))

    data.append(trace_data)
    layout = {'title':'Economic Indicators - {} - {}'.format(currency1,disp_col1)}

    return {
        'data':data,
        'layout': layout
    }

@app.callback(
    dash.dependencies.Output('events1', 'options'),
    [dash.dependencies.Input('currency1', 'value')])
def update_evets1(currency1):
    output = calendar[calendar.Currency == currency1]
    available_events1 = output.Event.unique()
    return [{'label': i, 'value': i} for i in available_events1]

@app.callback(
    dash.dependencies.Output('events1', 'value'),
    [dash.dependencies.Input('currency1', 'value')])
def update_evets1(currency1):
    output = calendar[calendar.Currency == currency1]
    available_events1 = output.Event.unique()
    return available_events1[0]


#   Right Graph ------------------------------------------------------------->>
@app.callback(
     dash.dependencies.Output('surprice_pct-ts2', 'figure'),
    [dash.dependencies.Input('currency2', 'value'),
     dash.dependencies.Input('events2', 'value'),
     dash.dependencies.Input('disp_col2', 'value'),
     dash.dependencies.Input('year_slider', 'value')])

def update_ts1(currency2,events2, disp_col2, year_slider):

    output = calendar[calendar.Currency == currency2]
    output = output[output.Event == events2]


    data = []
    trace_data = go.Bar(x=list(output.Date),
                        y=list(output[disp_col2]))

    data.append(trace_data)
    layout = {'title':'Economic Indicators - {} - {}'.format(currency2,disp_col2)}

    return {
        'data':data,
        'layout': layout
    }

@app.callback(
    dash.dependencies.Output('events2', 'options'),
    [dash.dependencies.Input('currency2', 'value')])
def update_evets1(currency2):
    output = calendar[calendar.Currency == currency2]
    available_events2 = output.Event.unique()
    return [{'label': i, 'value': i} for i in available_events2]

@app.callback(
    dash.dependencies.Output('events2', 'value'),
    [dash.dependencies.Input('currency2', 'value')])
def update_evets1(currency2):
    output = calendar[calendar.Currency == currency2]
    available_events2 = output.Event.unique()
    return available_events2[0]

if __name__ == '__main__':
    app.run_server(debug=True)

将解决方案缩减到125个字符,并接近您所想到的代码。