hack類型別名:Transparent

2018-11-21 10:22 更新

transparent (透明)類型別名是一個(gè)使用創(chuàng)建的type。

<?hh 
type  UserIDtoFriendIDsMap  =  Map < int , Vector < int >> ;

對(duì)于給定的類型,該類型和所有類型的透明別名都是相同的類型,并且可以自由交換 - 它們?cè)谒蟹矫嫱耆嗤?duì)于何處可以定義透明類型別名或哪些源代碼可以訪問其底層實(shí)現(xiàn)沒有限制。

opaque類型別名不同,由于沒有區(qū)別別名和別名類型,所以透明類型別名作為抽象機(jī)制并不是特別有用。他們的主要用例是定義一個(gè)簡寫類型的名字,增加可讀性并且保存輸入。考慮下面的函數(shù)簽名,以及沒有Matrix類型別名的話會(huì)有多麻煩:

<?hh

namespace Hack\UserDocumentation\TypeAliases\Transparent\Examples\Converted;

type Matrix<T> = Vector<Vector<T>>;

function add<T as num>(Matrix<T> $m1, Matrix<T> $m2): Matrix<num> {
  // Assumes that $m1 and $m2 have the same dimensions; real code should have
  // better error detection and handling of course.
  $r = Vector {};
  foreach ($m1 as $i => $row1) {
    $new_row = Vector {};
    foreach ($row1 as $j => $val1) {
      $new_row[] = $val1 + $m2[$i][$j];
    }
    $r[] = $new_row;
  }

  return $r;
}

function get_m1(): Matrix<int> {
  // No conversion needed from these Vectors into the Matrix return type, since
  // the two are equivalent.
  return Vector { Vector { 1, 2 }, Vector { 3, 4 } };
}

function get_m2(): Vector<Vector<int>> {
  return Vector { Vector { 5, 6 }, Vector { 7, 8 } };
}

function run(): void {
  var_dump(add(
    get_m1(),
    // get_m2() returns a Vector<Vector<int>>, and add() takes a Matrix<int>,
    // but no conversion is needed here since the two are equivalent.
    get_m2()
  ));
}

run();

Output

object(HH\Vector)#7 (2) {
  [0]=>
  object(HH\Vector)#8 (2) {
    [0]=>
    int(6)
    [1]=>
    int(8)
  }
  [1]=>
  object(HH\Vector)#9 (2) {
    [0]=>
    int(10)
    [1]=>
    int(12)
  }
}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)